为什么此代码会生成 NotSupportedException?

发布于 2024-08-30 13:51:43 字数 760 浏览 13 评论 0原文

为什么会抛出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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

想挽留 2024-09-06 13:51:43

编辑:好的,代码崩溃了,因为它不知道如何调用 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 your foo method does - foo() is a black box as far as it's concerned. It therefore can't translate it into SQL.

倾其所爱 2024-09-06 13:51:43

一旦您尝试迭代第二个版本,它就会失败。您不能在 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).

那些过往 2024-09-06 13:51:43

因为在第二个查询中没有执行实际的查询。尝试在 SingleOrDefault() 所在位置添加 ToList()

这可能是因为 SQL 生成功能无法确定如何处理您的 foo() 函数,因此无法为其生成输出。

Because in the 2nd query no actual query is executed. Try adding ToList() where SingleOrDefault() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文