演员价值型“的Int32”失败,因为物化值为null [英] The cast to value type 'Int32' failed because the materialized value is null

查看:440
本文介绍了演员价值型“的Int32”失败,因为物化值为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code。我得到的错误:

I have the following code. I'm getting error:

演员价值型的Int32失败,因为物化值为null。无论结果类型的泛型参数或查询必须使用可空类型。

"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 creditsSum = (from u in context.User
                  join ch in context.CreditHistory on u.ID equals ch.UserID                                        
                  where u.ID == userID
                  select ch.Amount).Sum();

如何修改查询,以接受空值?

How can I modify the query to accept null values?

推荐答案

一个LINQ到SQL查询不能执行,因为code,而是转换成SQL。有时候,这是一个漏抽象能产生意外的行为。

A linq-to-sql query isn't executed as code, but rather translated into SQL. Sometimes this is a "leaky abstraction" that yields unexpected behaviour.

这样的一个情况下是空的处理,其中可以存在于不同的地方意想不到的空值。 ... DefaultIfEmpty(0).SUM(0)可以在这个(很简单)的情况下,那里可能没有元素和SQL的帮助SUM 返回,而C#期望0。

One such case is null handling, where there can be unexpected nulls in different places. ...DefaultIfEmpty(0).Sum(0) can help in this (quite simple) case, where there might be no elements and sql's SUM returns null whereas c# expect 0.

一个更一般的方法是使用 ?? 将被翻译成 COALESCE 每当有风险生成的SQL返回意外空:

A more general approach is to use ?? which will be translated to COALESCE whenever there is a risk that the generated SQL returns an unexpected null:

var creditsSum = (from u in context.User
              join ch in context.CreditHistory on u.ID equals ch.UserID                                        
              where u.ID == userID
              select (int?)ch.Amount).Sum() ?? 0;

这首强制转换为诠释?告诉C#编译器,这当然pression的确可以返回,虽然和()返回 INT 。然后,我们使用普通的 ?? 运算符来处理情况。

This first casts to int? to tell the C# compiler that this expression can indeed return null, even though Sum() returns an int. Then we use the normal ?? operator to handle the null case.

基于这个答案,我写了一个博客文章详细规定双方的LINQ to SQL和LINQ to实体。

Based on this answer, I wrote a blog post with details for both LINQ to SQL and LINQ to Entities.

这篇关于演员价值型“的Int32”失败,因为物化值为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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