I'm hitting information overload when it comes to generating dynamic where clauses in EF. Some of the solutions look to be very dated (I'm targeting .NET 4.5 with EF 5).
Here's what I have:
public enum PersonTypes
{
Lazy = 1,
Awesome = 2,
SuperHero = 3
}
public bool IncludeLazyPeople { get; set; }
public bool IncludeAwesomePeople { get; set; }
public bool IncludeSuperHeroPeople { get; set; }
Using EF I need to query for the people types that match the supplied bools.
I looked into this: http://www.albahari.com/nutshell/predicatebuilder.aspx
And this is what I came up with:
// create an expression that would include none of the person types
var personTypeExpression = PredicateBuilder.False<DAL.Models.Person>();
if (IncludeLazyPeople)
personTypeExpression = personTypeExpression.Or(person => person.PersonType == (int)PersonTypes.Lazy);
if (IncludeAwesomePeople)
personTypeExpression = personTypeExpression.Or(person => person.PersonType == (int)PersonTypes.Awesome);
if (IncludeSuperHeroPeople)
personTypeExpression = personTypeExpression.Or(person => person.PersonType == (int)PersonTypes.SuperHero);
// filter the people for all included types
var filteredPeople = ctx.People.Where(personTypeExpression);
That failed to work because I didn't include the AsExpandable extension. Before I try that, I'm wondering if there is an easier approach?