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();
2
  • This looks like it might be a duplicate of "Combining two expressions (Expression<Func<T, bool>>)" stackoverflow.com/questions/457316/… Commented Nov 17, 2015 at 15:16
  • maybe use regular expressions Commented Nov 17, 2015 at 17:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.