PredicateBuilder返回所有用户谓词。或者

时间:2013-11-18 17:33:42

标签: c# linq entity-framework predicatebuilder

我正在使用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();

        [ ... ]
    }
}

if 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子句。

2 个答案:

答案 0 :(得分:5)

你的问题在这里:

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

代替。

答案 1 :(得分:1)

true OR something Or SomethingElse的结果是什么?

你甚至需要知道something是什么?

始终为true

您需要从False开始,而不是TrueFalse Or anything相当于anything

如果您正在使用AND项,那么您将从true开始,因为true AND anything等同于anything