0

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();
juharr
  • 31,741
  • 4
  • 58
  • 93
Lost_In_Library
  • 3,265
  • 6
  • 38
  • 70

1 Answers1

2

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

Chris Wyatt
  • 142
  • 8
  • Thank you for your answer. But I'm sorry, I can't do that for our abstraction. We are generating filter business code in service layer and pass it to data layer. That's why we need to build an expression and send it as method's parameter. – Lost_In_Library Nov 17 '15 at 12:45
  • @Lost_In_Library Then just restructure your layer so that it accepts a query and returns a query, rather than providing an expression. It's quite a bit easier that way. – Servy Nov 17 '15 at 15:26