我正在使用C#,Entity Framework Code First 4.4.0.0和.NET Framework 4.0开发一个库。
我有以下代码:
string[] keywords = null;
if (query_string != null)
keywords = query_string.Split(' ');
// Check parameter. It will throw an exception.
ParameterCheck.CheckObjectId(user_id);
// Convert parameter to int.
int userId = Int32.Parse(user_id);
try
{
using (var context = new AdnLineContext())
{
context.Configuration.ProxyCreationEnabled = false;
//IQueryable<User> query = context.Users;
IQueryable<User> query = context.Users.AsExpandable();
var predicate = PredicateBuilder.False<User>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(u => u.Name.Contains(temp) ||
u.State.Contains(temp) ||
u.HashTags.Contains(temp));
}
query.Where(predicate);
query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
[ ... ]
}
}
如果
keywords = {"john", "happy"}
我想获得此SQL:select * from users where
users.name like '%john%' or
users.state like '%john%' or
users.hashtags like '%john%' or
users.name like '%happy%' or
users.state like '%happy%' or
users.hashtags like '%happy%';
如何使用PredicateBuilder做到这一点?
顺便说一句,我已经从http://www.albahari.com/nutshell/predicatebuilder.aspx下载了LinqKit
更新
我在
var users = query.ToList();
处添加了一个断点,并且query
具有以下SQL:{SELECT
[Extent1].[UserId] AS [UserId],
[...]
FROM [dbo].[Users] AS [Extent1]}
它没有
Where
子句。 最佳答案
您的问题在这里:
query.Where(predicate);
query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
.Where
和.Include
不会修改基础查询,它们会返回一个新查询。使用
query = query.Where(predicate);
query = query.Include("WhoHasBlockedMe").Include("Friends");
var users = query.ToList();
代替。