Reputation: 4179
LINQ,
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);
These two where clauses are chained together as;
WHERE ([t0].[gid] = 0) AND (([t1].[uid] = 1) OR ([t1].[uid] = 2))
How do I add the two where conditions as
WHERE ([t0].[gid] = 0) OR (([t1].[uid] = 1) OR ([t1].[uid] = 2))
Upvotes: 2
Views: 2067
Reputation: 10408
Instead of doing multiple Or clauses, why not just do Contains. That way your list of Ids can be complete dynamic (as long as it doesn't exceed 2000):
var ids = new int[] {1, 2, 3};
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)
&& ids.Contains(u.uid)
select u);
Upvotes: 0
Reputation: 4179
Thanks to,
Can PredicateBuilder generate predicates that span multiple tables?
I now have a solution that works but my result set is based on a new hybrid class. As a result I have had to mirror all of the relevant fields. See below.
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; }
}
With this class I can now do the following;
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);
Upvotes: 2
Reputation: 1627
var usersInGroup = (from u in db.Users
join g in db.Groups
on u.uid equals g.uid
where g.gid.Equals(0) || (u.uid.Equals(1) || u.uid.Equals(2))
select u)
Upvotes: 0