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

我的未来我决定 提交于 2020-01-21 05:22:06

问题


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


来源:https://stackoverflow.com/questions/3784005/can-i-use-custom-delegate-method-in-where-method-of-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!