Can I use custom delegate method in Where method o

2019-02-14 12:15发布

问题:

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:

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);