为什么此代码会生成 NotSupportedException?
为什么会抛出System.NotSupportedException?
string foo(string f) { return f; }
string bar = "";
var item = (from f in myEntities.Beer
where f.BeerName == foo(bar)
select f).FirstOrDefault();
编辑:这是一个 MSDN 参考 (有点)解释了事情......
LINQ to Entities 中的任何方法调用 未显式映射的查询 到一个规范函数将导致 运行时 NotSupportedException 抛出异常。欲了解以下列表 映射到的 CLR 方法 规范函数,请参阅 CLR 方法 规范函数映射。
另请参阅 http://mosesofegypt.net/post/ LINQ-to-Entities-what-is-not-supported.aspx
Why does this throw System.NotSupportedException?
string foo(string f) { return f; }
string bar = "";
var item = (from f in myEntities.Beer
where f.BeerName == foo(bar)
select f).FirstOrDefault();
Edit: Here's an MSDN reference that (kind of) explains things...
Any method calls in a LINQ to Entities
query that are not explicitly mapped
to a canonical function will result in
a runtime NotSupportedException
exception being thrown. For a list of
CLR methods that are mapped to
canonical functions, see CLR Method to
Canonical Function Mapping.
See also http://mosesofegypt.net/post/LINQ-to-Entities-what-is-not-supported.aspx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:好的,代码崩溃了,因为它不知道如何调用
foo()
。查询被构建为表达式树,然后转换为 SQL。表达式树翻译器知道各种事情 - 例如字符串相等性和各种其他方法(例如
string.StartsWith
),但它不知道您的foo 是什么
方法的作用 -foo()
就其而言是一个黑匣子。因此它无法将其转换为 SQL。EDIT: Okay, the code blows up because it doesn't know what to do with the call to
foo()
. The query is built up as an expression tree which is then converted to SQL.The expression tree translator knows about various things - such as string equality, and various other methods (e.g.
string.StartsWith
) but it doesn't know what yourfoo
method does -foo()
is a black box as far as it's concerned. It therefore can't translate it into SQL.一旦您尝试迭代第二个版本,它就会失败。您不能在
IQueryable<>
where
子句中使用本地定义的方法(当然可以,但当 LINQ 提供程序尝试转换它时,它会失败到 SQL)。The second version will fail as soon as you try to iterate over it. You can't use a locally defined method in an
IQueryable<>
where
clause (of course, you can, but it will fail when the LINQ provider tries to translate it into SQL).因为在第二个查询中没有执行实际的查询。尝试在
SingleOrDefault()
所在位置添加ToList()
。这可能是因为 SQL 生成功能无法确定如何处理您的
foo()
函数,因此无法为其生成输出。Because in the 2nd query no actual query is executed. Try adding
ToList()
whereSingleOrDefault()
is.It's probably because the SQL-generation functionality isn't able to determine what to do with your
foo()
function, so can't generate output for it.