linq-to-entity动态查询

时间:2014-04-28 06:39:06

标签: c# linq linq-to-entities

我目前正在将旧系统迁移到.Net,但我遇到了这个问题。 我想返回结果,但我仍然需要在函数之后对其进行优化,但是使用这段代码,我没有选择,只能从数据库中调用结果并过滤内存中的结果而不是性能不佳。

public IQueryable<User> GetUser(string[] accessCodes)
{
    string condition = "";
    if (accessCodes == null)
    {
         condition = " AccessCode IS NOT NULL "
    }
    else
    {
        for (int i = 0; i <= accessCodes.Length - 1; i++)
        {
            condition += " AccessCode LIKE '%" + accessCodes[i].ToString() + "%' ";
            if (i + 1 <= code.Length - 1)
            {
                condition += " OR ";
            }
        }
    }

    return context.ExecuteQuery<User>("SELECT * FROM User WHERE " + condition, null).ToList();
}

我尝试过这种方法但是我被卡住了:

public IQueryable<User> GetUser(string[] accessCodes)
{
    IQueryable<User> basequery = from u in context.User 
                                 select u;

    if (accessCodes == null)
    {
         basequery = basequery.Where(n => n.AccessCode != null);
    }
    else
    {
        for (int i = 0; i <= accessCodes.Length - 1; i++)
        {
            // what am I supposed to do here?
        }
    }

    return basequery;
}

我希望有些解决方案不需要第三方库。

2 个答案:

答案 0 :(得分:1)

您可以尝试Any

else
{
    output = output.Where(u => accessCodes.Any(a => u.AccessCode.Contains(a)));
}

或者您可以使用PredicateBuilder

if (accessCodes == null)
{
    output = output.Where(u => u.AccessCode == null);
}
else
{
    var predicate = PredicateBuilder.False<User>();

    for (int i = 0; i <= accessCodes.Length - 1; i++)
    {
        predicate = predicate.Or(u => u.AccessCode.Contains(accessCodes[i]))
    }

    output = output.Where(predicate);
}

我还更改了您的if部分:Where方法不修改源代码,它会返回新的查询定义,因此您必须将其分配回output才能使其正常工作。< / p>

答案 1 :(得分:1)

这应该适合你:

IQueryable<User> basequery = from u in context.User 
                             select u;
if (accessCodes == null)
{
    basequery = basequery.Where(u => u.AccessCode != null);
}
else
{
    basequery = basequery.Where(u => accessCodes.Contains(u=>u.AccessCode));
}

还要确保您返回basequery,因为您的方法中的output未定义且未使用。