条件将仅在运行时指定
我尝试使用一个条件动态地连接两个表,它工作正常。 但动态有两个或两个以上的条件,它不起作用。请帮我解决这个问题
请查看案例
案例1:加入一个条件(正常工作)
Base entity:User
entity to join :Role
condition to join: Role.Id = User.RoleId
//select * from User inner join Role on User.RoleId=Role.Id
//static way
IQueryable<UserEntity> query =
db.Set<user>().Join(db.Set<Role>(),
user => User.RoleId,
role=> role.Id,
(user , role) => new { user , role }).Select(temp=> temp.user);
//Dynamic Way **(working fine)**
ParameterExpression lambdaExprVar_Role = Expression.Parameter(typeof(Role), "role");
PropertyInfo rightPropertyInfo_role = typeof(Role).GetProperty("Id");
Expression rightExpression_role = Expression.Property(lambdaExprVar_Role, rightPropertyInfo_role );
Expression<Func<Role, Int64>> myexp_role = Expression.Lambda<Func<Role, Int64>>(rightExpression_role , new ParameterExpression[] { lambdaExprVar_Role });
ParameterExpression lambdaExprVar_User = Expression.Parameter(typeof(User), "user");
PropertyInfo rightPropertyInfo_user = typeof(User).GetProperty("RoleId");
Expression rightExpression_user = Expression.Property(lambdaExprVar_User, rightPropertyInfo_user);
Expression<Func<User, Int64>> myexp_user = Expression.Lambda<Func<User, Int64>>(rightExpression_user, new ParameterExpression[] { lambdaExprVar_User });
IQueryable<OrganizationNode> query = db.Set<User>()
.Join(db.Set<Role>(), myexp_user, myexp_role, (user, role) => new {user, role})
.Select(temp=>temp.user);
案例2:加入两个条件(不工作)
Base entity:User
entity to join :Role
condition to join: Role.Id==User.RoleId,Role.Code==User.RoleCode
//select * from User inner join Role on User.RoleId=Role.Id and User.RoleCode=Role.Code
//static way **(working fine)**
IQueryable<User> query =
db.Set<user>().Join(db.Set<Role>(),
**user => new { matchId = user.RoleId, matchcode= user.RoleCode},
role=> new { matchId = role.Id, matchcode= role.code},**
(user , role) => new { user , role }).Select(temp=> temp.user);
//Dynamic Way (**** not working)
帮我写/重写代码。
答案 0 :(得分:0)
试试这个
from u in db.Set<user>
inner join r in db.Set<Role>
on new {r.Id, r.Code} equals {u.RoleId, u.RoleCode)
select u
编写上述linq查询的另一种方法如下:
from u in db.Set<user>
from r in db.Set<Role>.Where(r.Id==RoleId && u.RoleCode==r.Code)
select u