1

I am using Entity Framework code first and I have code like this:

var foos = context.Foos.Where(f => f.Bar == "Hello World").ToList();

Using an SQL profiler, I see that the script run against the database contained a WHERE statement, as expected.

But when I put the Where predicate in a variable:

Func<Foo, bool> predicate = f => f.Bar == "Hello World");
var foos = context.Foos.Where(predicate).ToList();

the resulting SQL command no longer contains a WHERE statement.

Is there a way that this can work?

1
  • What does it include instead of a WHERE? Commented Mar 5, 2015 at 3:00

2 Answers 2

1

Change to Expression<Func<Foo, bool>>

Expression<Func<Foo, bool>> predicate = f => f.Bar == "Hello World";
Sign up to request clarification or add additional context in comments.

Comments

0

LinqKit could solve this kind issues. It can be obtained by nuget.

An example about using PredicateBuilder of LinqKit.

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}

How it works

var predicate = PredicateBuilder.True <Product> ();

// is just a shortcut for this:
Expression<Func<Product, bool>> predicate = c => true;

Comments

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.