Linq - 动态构建 LINQ 查询时模拟 OrWhere 表达式?
搜索下面的代码片段允许用户将字符串与表中的三个字段进行匹配。如果任何字段匹配,则该条目将包含在结果中。但是,使用Where 过滤结果会导致“字符串必须匹配所有三个字段”,而不是“字符串可以匹配三个字段中的任何一个”。
动态构建 LINQ 查询时有没有办法模拟 OrWhere 表达式?
var foundUsers = from UserInfo user in entities.UserInfo
select user;
if (searchCompleteName)
{
foundUsers = foundUsers.Where(u => u.CompleteName.Contains(searchString));
}
if (searchPortalID)
{
foundUsers = foundUsers.Where(u => u.PortalID.Contains(searchString));
}
if (searchUsername)
{
foundUsers = foundUsers.Where(u => u.UserIdentity.Contains(searchString));
}
附言。我正在使用 Entities Framework 和 LINQ to Entities,并且正在开发 MVC3 Web 应用程序。
The code snippet below search allow the user to match a string against three fields in the table. If any of the fields match, the entry is included in the result. However, using Where to filter out the results is resulting in "the string must match all three fields" instead "the string can match any of the three fields".
Is there a way to simulate an OrWhere expression when building LINQ queries dynamically?
var foundUsers = from UserInfo user in entities.UserInfo
select user;
if (searchCompleteName)
{
foundUsers = foundUsers.Where(u => u.CompleteName.Contains(searchString));
}
if (searchPortalID)
{
foundUsers = foundUsers.Where(u => u.PortalID.Contains(searchString));
}
if (searchUsername)
{
foundUsers = foundUsers.Where(u => u.UserIdentity.Contains(searchString));
}
PS. I am using Entities Framework and LINQ to Entities, and am doing a MVC3 Web Application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:- http://www.albahari.com/nutshell/predicatebuilder.aspx
Try this:- http://www.albahari.com/nutshell/predicatebuilder.aspx
不太漂亮,但它会起作用。
您也可以通过工会来做到这一点。联合运算符返回不同的结果,因此不会有任何重复。我不知道 EF 是否可以将其推迟到数据库。
Not exactly pretty, but it would work.
You could also do this with a union. The union operator returns distinct results so there will not be any duplicates. I have no idea if EF can defer this to the database.