问题
Using entity framework to return a list of people where the forename contains text in a string array.
Let's say:
string[] search = new string[] { "bert", "rob" };
and query
dataContext.People.Where(w => search.Any(a => w.Forename.Contains(a)));
This compiles and works BUT the process is actually calling all records from the database and then performing my where clause on the returned data. This makes sense.
Is there a way to rewrite the query so the where clause is generated in SQL?
回答1:
I assume that dataContext.People is an IQueryable
from the DbSet
and that there is no materialization instruction involved such as ToList()
or AsEnumerable()
.
the answer is here: http://www.albahari.com/nutshell/predicatebuilder.aspx
in your case:
var predicate = PredicateBuilder.False<People>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Forename.Contains (temp));
}
dataContext.People.Where (predicate);
回答2:
One way to do this is to use SqlQuery and perform and actual SQL query.
dataContext.Database.SqlQuery<People>("SELECT Forename, Lastname FROM myTable WHERE Forename LIKE '%bert%' or Forename LIKE '%rob%'");
来源:https://stackoverflow.com/questions/43874298/entity-framework-query-using-contains-with-mulitple-options