Reputation: 3493
I'm using entity framework 6.1.3 and .net framework 4.5.1 with C# lang.
What I want to do is; I want to combine expressions with if-else statements.
Here is my expression
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));
to
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();
Upvotes: 0
Views: 139
Reputation: 142
If this is specifically for use with EF queries then you might find it easier to chain Where() calls to achieve the same effect.
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();
*Edit
You could try using this third-party library, PredicateBuilder http://www.albahari.com/nutshell/predicatebuilder.aspx
Upvotes: 2