我使用实体框架6.1.3和.net框架4.5.1与C#lang。
我想做的是;我想将表达式与if-else语句结合起来 这是我的表达
Expression<Func<Article, bool>> expression =
q => (!newsDayStart.HasValue || q.PublishedOn >= newsDayStart) &&
(!newsDayEnd.HasValue || q.PublishedOn <= newsDayEnd) &&
(!categoryId.HasValue || q.CategoryId == categoryId.Value) &&
(string.IsNullOrEmpty(searchText) || q.Title.Contains(searchText) &&
(!isActive != null || q.IsActive == isActive.Value));
到
Expression<Func<Article, bool>> expression = ......;
if ( newsDayStart.HasValue )
{
//Obviosly += this statement will not work.
expression += q => q.PublishedOn > = newsDayStart
}
//TODO write other if else statements...
//Send expression
_context.Articles.Where(expression).Count();
答案 0 :(得分:2)
如果这是专门用于EF查询,那么您可能会发现链接Where()调用更容易实现相同的效果。
Expression<Func<Article, bool>> expression = ......;
//Send expression
var query = _context.Articles.Where(expression)
if ( newsDayStart.HasValue )
{
query = query.Where(q => q.PublishedOn > = newsDayStart);
}
query.Count();
<强> *修改
您可以尝试使用此第三方库PredicateBuilder http://www.albahari.com/nutshell/predicatebuilder.aspx