我可以在实体框架的 Where 方法中使用自定义委托方法吗? [英] Can I use custom delegate method in Where method of Entity Framework?

查看:16
本文介绍了我可以在实体框架的 Where 方法中使用自定义委托方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我将参数传递给 Where 方法如下: f =>f.Id >4.我可以通过委托方法而不是 f.Id >4?

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

推荐答案

没有.

实体框架需要能够查看正在尝试的所有内容.

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

DelegateFunc 的定义如下所示:

Where the definition of DelegateFunc looks like this:

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

实体框架无法窥视委托内部,将其打开并将其转换为 SQL.

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

但一切都没有丢失.

如果您的目标是重复使用常见的过滤器等,您可以这样做:

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

这篇关于我可以在实体框架的 Where 方法中使用自定义委托方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆