使用包含多个选项的实体框架查询 [英] Entity Framework Query using Contains with mulitple options

查看:73
本文介绍了使用包含多个选项的实体框架查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实体框架返回姓名包含字符串数组中文本的人员列表。

Using entity framework to return a list of people where the forename contains text in a string array.

让我们说:

string[] search = new string[] { "bert", "rob" };

并查询

dataContext.People.Where(w => search.Any(a => w.Forename.Contains(a)));

这将编译并运行,但是该过程实际上是从数据库中调用所有记录,然后执行where子句在返回的数据上。

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.

有没有一种方法可以重写查询,以便在SQL中生成where子句?

Is there a way to rewrite the query so the where clause is generated in SQL?

推荐答案

我假设dataContext.People是< IQueryable code> DbSet ,并且不涉及实现指令,例如 ToList() AsEnumerable()

I assume that dataContext.People is an IQueryable from the DbSet and that there is no materialization instruction involved such as ToList() or AsEnumerable().

答案在这里: http://www.albahari.com/nutshell/predicatebuilder.aspx

在您的情况下:

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);

这篇关于使用包含多个选项的实体框架查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆