Nullable上的 OrderBy在实体框架中具有默认值
我们正在迁移一些代码以使用实体框架,并有一个查询尝试对可为 Nullable 字段进行排序,并使用 Nullable.GetValueOrDefault(T) 函数。
但是,执行后会返回以下错误:
LINQ to Entities 无法识别“Int32 GetValueOrDefault(Int32)”方法,并且此方法无法转换为存储表达式。
查询如下所示:
int magicDefaultSortValue = 250;
var query = context.MyTable.OrderBy(t => t.MyNullableSortColumn
.GetValueOrDefault(magicDefaultSortValue));
来自 这个答案我可以看到有一种方法可以在您的 EDMX 中提供“翻译”。我们可以为这个合并函数写一个类似的翻译吗?
注意:当我尝试时,查询中的 ??
合并运算符而不是 GetValueOrDefault 确实有效。那么,也许无论什么因素都可以发挥作用?
We are migrating some code to use Entity Framework and have a query that is trying to sort on a Nullable field and provides a default sort value is the value is null using the Nullable.GetValueOrDefault(T) function.
However, upon execution it returns the following error:
LINQ to Entities does not recognize the method 'Int32 GetValueOrDefault(Int32)' method, and this method cannot be translated into a store expression.
The query looks like:
int magicDefaultSortValue = 250;
var query = context.MyTable.OrderBy(t => t.MyNullableSortColumn
.GetValueOrDefault(magicDefaultSortValue));
From this answer I can see that there is a way to provide "translations" within your EDMX. Could we write a similar translation for this coalescing function?
NOTE: When I tried, the ??
coalescing operator instead of GetValueOrDefault in the query it does work. So perhaps whatever makes that work could be leveraged?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信你已经找到了答案。当您使用
??
时,EF 使用CASE
生成 SQL 来选择排序值(如果该值为null
),然后对其进行排序。将生成以下 sql:
顺便说一句,我建议使用 LINQPad ,它可以让您使用 EF 模型并查看正在生成的sql。此外,了解 EntityFunctions 类和 SqlFunctions 类,因为它们提供对几个有用函数的访问。
I believe you found your answer. When you use
??
, EF generates SQL using aCASE
to select your sort value if the value isnull
, and then sorts on that.will generate the following sql:
As an aside, I would recommend getting LINQPad which will let you work with your EF models and view the sql being generated. Also, it is helpful to know about the EntityFunctions class and SqlFunctions class as they provide access to several useful functions.