Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use custom delegate method in Where method of Entity Framework?

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?

like image 916
Linh Avatar asked Sep 24 '10 03:09

Linh


Video Answer


1 Answers

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);
like image 103
Alex James Avatar answered Sep 22 '22 18:09

Alex James