gpt4 book ai didi

c# - LINQ LEFT JOIN,用 OR 组合多个 WHERE 子句

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:22 25 4
gpt4 key购买 nike

林奇,

var clause = PredicateBuilder.False<User>();
clause = clause.Or(u => u.uid.Equals(1));
clause = clause.Or(u => u.uid.Equals(2));

var usersInGroup = (from u in db.Users
join g in db.GroupUsers
on u.uid equals g.uid
into ug
from g in ug.DefaultIfEmpty()
where g.gid.Equals(0)
select u).Where(clause);

这两个 where 子句链接在一起;

WHERE ([t0].[gid] = 0) AND (([t1].[uid] = 1) 或 ([t1].[uid] = 2))

如何添加两个where条件

WHERE ([t0].[gid] = 0) (([t1].[uid] = 1) 或 ([t1].[uid] = 2))

最佳答案

感谢,

Can PredicateBuilder generate predicates that span multiple tables?

我现在有了一个可行的解决方案,但我的结果集是基于一个新的混合类。结果,我不得不反射(reflect)所有相关领域。见下文。

public class HybridGroupUser {
private User _user;
public User User {
get { return _user; }
set {
_user = value;
if (value != null) {
uid = value.uid;
fname = value.fname;
lname = value.lname;
email = value.email;
}
}
}
private GroupUser _GroupUser;
public GroupUser GroupUser {
get { return _GroupUser; }
set {
_GroupUser = value;
if (value != null) {
uid = value.uid;
fname = value.fname;
lname = value.lname;
email = value.email;
}
}
}

public int? uid { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string email { get; set; }
}

有了这个类(class),我现在可以做以下事情;

var clause = PredicateBuilder.False<HybridGroupUser>();

clause = clause.Or(u => u.GroupUser.gid.Equals(0);
foreach (int i in AddedUsers) {
int tmp = i;
clause = clause.Or(u => u.User.uid.Equals(tmp));
}

var usersInGroup = (from u in db.Users
join gusr in db.GroupUser
on u.uid equals gusr.uid
into ug
from gusr in ug.DefaultIfEmpty()
select new HybridGroupUser {
User = u,
GroupUser = gusr
}).Where(clause);

关于c# - LINQ LEFT JOIN,用 OR 组合多个 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6456688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com