实体框架链接在where子句中

时间:2011-08-05 17:42:16

标签: linq entity-framework entity-framework-4.1

是否有可能重构以下查询,因此i.Title.Contains(query) || i.Description.Contains(query)在生成的sql中保持单个查询(无子查询)时只有一次?

if (extendedSearch)
{
    result = result.Where(i => i.Title.Contains(query) || i.Description.Contains(query)
        || (i.CreatedBy.FirstName + " " + i.CreatedBy.LastName).Contains(query)
        || (i.AssignedTo.FirstName + " " + i.AssignedTo.LastName).Contains(query)
    );
}
else
    result = result.Where(i => i.Title.Contains(query) || i.Description.Contains(query));

2 个答案:

答案 0 :(得分:4)

result = result.Where(i => 
    i.Title.Contains(query) || i.Description.Contains(query)
 || (extendedSearch && 
      ((i.CreatedBy.FirstName + " " + i.CreatedBy.LastName).Contains(query)
   ||  (i.AssignedTo.FirstName + " " + i.AssignedTo.LastName).Contains(query))));

(保持手指交叉,括号是正确的......)

Where表达式中的逻辑结构: A或(extendedSearch和B)

如果extendedSearch false ,则结果仅取决于 A 。如果extendedSearch 为真,则结果取决于(A或B) - 这表示查询中的逻辑,我希望。

答案 1 :(得分:1)

我现在无法为自己验证此解决方案,但它必须是类似的(TI是您的代码示例中的一种类型):

Func<TI, Boolean> predicate = i => i.Title.Contains(query) ||i.Description.Contains(query);

if (extendedSearch){
result = result.Where( i=>predicate(i) 
    || (i.CreatedBy.FirstName + " " + i.CreatedBy.LastName).Contains(query)
    || (i.AssignedTo.FirstName + " " + i.AssignedTo.LastName).Contains(query)
); } else result = result.Where(predicate);

是你在寻找什么?