The following simple example shows how it is possible to create a reusable predicate separated into a method of its own and call this method in Linq to entities code. Make note of the use of the AsExpandable() extension method that transforms the DbSet into an IQueryable by returning a wrapper that allows this. The code is run inside LinqPad. Make note that LinqPad has got inherent support for PredicateBuilder, but the LinqKit DLL was added as a reference. Also the namespace imports added where: System.Linq, System.Linq.Expressions and LinqKit. Press F4 to set up the additional references and imports in Linqpad.
public Expression<Func<Patient, bool>> InterestingPatient(params string[] keywords){ var predicate = PredicateBuilder.False<Patient>(); foreach (string keyword in keywords){ string temp = keyword; predicate = predicate.Or(p => p.Name.Contains(temp)); } return predicate; } void Main() { Patients.AsExpandable().Where(InterestingPatient("Olsen", "Nilsen")).Dump(); }
The following images shows the output. Make note that Patient here is a table in the context of my project. The data shown here is test data (not real pasients of course):