Entity Framework Query using Contains with mulitple options

白昼怎懂夜的黑 提交于 2019-12-30 07:22:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!