实体框架在记录上调用MAX为null [英] Entity Framework calling MAX on null on Records

查看:96
本文介绍了实体框架在记录上调用MAX为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



转换为值类型Int32失败,因为物化值为空。
结果类型的泛型参数或查询必须使用可空类型。

  var version = ctx.Entries 
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e => e.Version);

现在我明白为什么这会发生我的问题是如何做最好的方法如果表可以空的下面的代码解决了这个问题,但是它的非常丑陋的是没有MaxOrDefault()概念?

  int? version = ctx.Entries 
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Select(e =>(int?)e.Version)
的.max();


解决方案

是的,转换为Nullable T是推荐的方式处理LINQ to Entities查询中的问题。拥有一个具有正确签名的MaxOrDefault()方法听起来像一个有趣的想法,但是您只需要为呈现此问题的每个方法添加一个附加版本,这不会很好地扩展。



这是CLR中的工作方式与数据库服务器的实际工作之间的许多不匹配之一。 Max()方法的签名已经这样定义,因为结果类型预计与CLR上的输入类型完全相同。但是在数据库服务器上,结果可以为null。因此,您需要输入输入(尽管取决于您如何编写查询,可能足以将输出转换为T的可空)。



这里是一个看起来比上面略微简单的解决方案:

  var version = ctx.Entries 
.Where e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e =>(int?)e.Version);

希望这有帮助。


When calling Max() on an IQueryable and there are zero records I get the following exception.

The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

var version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Max(e => e.Version);

Now I understand why this happens my question is how is the best way to do this if the table can be empty. The code below works and solves this problem, but its very ugly is there no MaxOrDefault() concept?

int? version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Select(e => (int?)e.Version)
    .Max();

解决方案

Yes, casting to Nullable of T is the recommended way to deal with the problem in LINQ to Entities queries. Having a MaxOrDefault() method that has the right signature sounds like an interesting idea, but you would simply need an additional version for each method that presents this issue, which wouldn't scale very well.

This is one of many mismatches between how things work in the CLR and how they actually work on a database server. The Max() method’s signature has been defined this way because the result type is expected to be exactly the same as the input type on the CLR. But on a database server the result can be null. For that reason, you need to cast the input (although depending on how you write your query it might be enough to cast the output) to a Nullable of T.

Here is a solution that looks slightly simpler than what you have above:

var version = ctx.Entries 
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId) 
    .Max(e =>(int?)e.Version);

Hope this helps.

这篇关于实体框架在记录上调用MAX为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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