views:

30

answers:

1
Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);

I pass parameter to Where method as follows: "f => f.Id > 4". Can i pass a delegate method instead of "f.Id > 4"?

+1  A: 

No.

The Entity Framework needs to be able to see everything that is being attempted.

So if you simply did something like this:

queryable.Where(f => DelegateFunc(f));

Where the definition of DelegateFunc looks like this:

public bool DelegateFunc(Foo foo)
{
   return foo.Id > 4;
}

The Entity Framework has no way of peering inside the delegate, to crack it open and convert it to SQL.

All is not lost though.

If your goal is to re-use common filters etc you can do something like this instead:

public Expression<Func<Foo, bool>> DelegateExpression{
   get{
       Expression<Func<Foo,bool>> expr = f => f.Id > 4;
       return expr;
   }
}

queryable.Where(DelegateExpression);
Alex James
You are wrong, Alex. I pass to Where method as follows: "queryable.Where(f => DelegateFunc);" instead of "queryable.Where(f => DelegateFunc(f));". The statement executed successfully but it returned an Enumerable not Queryable.
Linh
I beg to differ. Generally when executing a filter you want to convert it to SQL. Getting an IEnumerable proves that you are NOT executing the filter in the database, instead LINQ to objects it taking over, and you are retrieving every record in the database and filtering in memory. Might work okay in testing, but once you have a lot of data it will perform awfully. Essentially you are using EF only to materialize entities, which is an anti-pattern.
Alex James
Your comment is very useful, Alex. It has shown the defect of performance in my way. Instead of passing a delegate method, I will pass an Expression<TSource, Func<Tsource, TResult>>, which is returned by a method. In that method I can custom the condition.
Linh
Alex, why do you know LINQ will take every record in the database and filtering in memory? where did you read article, blog or documentation?
Linh
I worked on the Entity Framework product team at Microsoft. But more importantly if you don't have an query as an expression there is no way to convert it to SQL. That is why LINQ and expressions was invented. Oh and BTW I think I deserve an accept here!
Alex James