user4144972
user4144972

Reputation: 47

How to use dynamic EF Query with OR values

How to use dynamic EF Query with OR values. I want to get out all people in PeopleGroups 3 or 4 this time, but next time perhaps PeopleGroups 5 or 8

This work, hardcoded. PeopleGroups is not primary Id

var Peoples = db.People.Where(_ => (_.PeopleGroups == 3 || _.PeopleGroups == 4));

But how to get it dynamic? I thought of .Contains() but its only work with primary Id I think

var searchPeopleGroups = new List<int> { 3, 4 };  
var Peoples = db.People.Where(_ => searchPeopleGroups.Contains(_.PeopleGroups));

Upvotes: 0

Views: 81

Answers (1)

mallocation
mallocation

Reputation: 241

The .Contains() method will work, and should generate an IN clause in the resulting SQL query.

If you want a truly dynamic solution, that generates an OR statement in the resulting SQL query, I suggest using the LinqKit framework, along with the included PredicateBuilder class.

If you include LinqKit, your query can become something similar to:

Expression<Func<People, bool>> predicate = PredicateBuilder.False<People>();

foreach (var g in searchPeopleGroups)
{
    predicate = predicate.Or(p => p.PeopleGroups == g);
}

var Peoples = db.People.AsExpandable().Where(predicate.Expand());

Upvotes: 1

Related Questions