无法将扩展方法转换为存储表达式
我有一个扩展方法如下:
public static bool SatisfiesSomeCondition(this Post post, SomeObj someObj)
{
return post.SomeObjId == someObj.SomeObjId;
}
我尝试像这样使用它:
var query = ctx.Posts.Where(p => p.SatisfiesSomeCondition(someObj)).ToList();
但我收到错误:
LINQ to Entities 无法识别“Boolean SatisfiesSomeCondition(xx.xx.xx.Post, xx.xx.xx.SomeObj)”方法,并且此方法无法转换为存储表达式。
如果我将查询更改为:
var query = ctx.Posts.Where(p => p.SomeObjId == someObj.SomeObjId).ToList();
这与方法相同。
它工作正常,并执行预期的 T-SQL。
为什么我的第一个查询不起作用?这是一个静态方法,它不能弄清楚如何创建表达式树吗? (例如 WHERE 过滤器)。我当然不必首先具体化查询吗? (这意味着我不想通过网络返回记录,并且我正在此处进行分页/排序,因此这不是一个选项)。
当然,我可以只使用有效的方法(例如上面的方法),但是方法 SatisfiesSomeCondition
是跨域使用的现有方法,我想重用该功能,而不是重复它。
有什么想法吗?
I have an extension method as follows:
public static bool SatisfiesSomeCondition(this Post post, SomeObj someObj)
{
return post.SomeObjId == someObj.SomeObjId;
}
And i'm trying to use it like this:
var query = ctx.Posts.Where(p => p.SatisfiesSomeCondition(someObj)).ToList();
But i get the error:
LINQ to Entities does not recognize the method 'Boolean SatisfiesSomeCondition(xx.xx.xx.Post, xx.xx.xx.SomeObj)' method, and this method cannot be translated into a store expression.
If i change the query to:
var query = ctx.Posts.Where(p => p.SomeObjId == someObj.SomeObjId).ToList();
Which is identical to the method.
It works fine, and executes the expected T-SQL.
Why doesn't my first query work? It's a static method, can't it figure out how to create the expression tree? (e.g a WHERE filter). Surely i don't have to materialize the query first? (which means the records i don't want come back over the wire, and i'm doing paging/ordering here, so that's not an option).
Of course, i can just go with what works (e.g the above), but the method SatisfiesSomeCondition
is an existing method used across the domain and i want to re-use that functionality, not duplicate it.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其更改为:
并像这样使用它:
这样它应该可以工作。您可以在单个查询中组合多个
Where
条件,因此它至少应该为您提供基本的可重用性。Change it to:
and use it like:
This way it should work. You can combine multiple
Where
conditions in single query so it should offer you at least basic reusablity.LINQ to Entities 引擎无法知道静态方法的作用。
LINQ 查询只能从表达式树转换。
The LINQ to Entities engine has no way of knowing what your static method does.
LINQ queries can only be translated from expression trees.