开发者

Entity Framework chained where clause

Is it possible to refactor following query so i.Title.Contains(query) || i.Description.Contains(query) is there only once while staying within single query (no subqueries开发者_StackOverflow) in the resulting 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));


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

(keeping fingers crossed that brackets are correct...)

Logical structure in Where expression: A or (extendedSearch and B)

If extendedSearch is false the result depends only on A. If extendedSearch is true the result depends on (A or B) - which represents the logic in your query, I hope.


I could not verify this solution for myself right now, but it must be something like that (TI is a type of i in your code sample):

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

is that what you are looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜