Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 转换为值类型';Int32';由于物化值为null,因此失败。_C#_Asp.net_Asp.net Mvc 4 - Fatal编程技术网

C# 转换为值类型';Int32';由于物化值为null,因此失败。

C# 转换为值类型';Int32';由于物化值为null,因此失败。,c#,asp.net,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc 4,我的asp.net mvc web应用程序中有以下代码:- SystemInformation s = new SystemInformation() { AssetCount = new AssetCount() { CustomerCount = entities.AccountDefinitions == null ? 0 : entities.AccountDefinitions.Count(),

我的asp.net mvc web应用程序中有以下代码:-

SystemInformation s = new SystemInformation()
            {
AssetCount = new AssetCount() {

                CustomerCount = entities.AccountDefinitions == null ? 0 : entities.AccountDefinitions.Count(),
                RackCount = tms.TMSRacks == null ? 0 : tms.TMSRacks.Count(),
                ServerCount = tms.TMSServers == null ? 0 : tms.TMSServers.Count(),
                CustomCount = tms.CustomAssets==null? 0 : tms.CustomAssets.Sum(a => a.Quantity)

            },
但当前,如果任何可枚举项为空,我将得到以下错误:-

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


问题可能是
tms.CustomAssets
集合为空。 要修复此问题,请编写如下内容:

var tmpCustomCount = tms.CustomAssets.Sum(a => (int?)a.Quantity);

...
AssetCount = new AssetCount() 
{
...
   CustomCount = tmpCustomCount ?? 0
}

这是因为int32是一种基本类型而不是对象,因此不可为null。试试这篇文章的建议。TL;DR:当使用语法
int32声明RackCount(例如)时?机架数或<代码>可为空的机架计数首先,您不应该让这些集合中的任何集合为null。应该不需要这些支票。请记住,对于一个集合来说,null和empty是两个截然不同的东西。@Grant是的,我有点累了,我在发布后看到了这一点。我不知道求和法的组成。它可能来自返回null的错误吗?@Sidewinder94当您试图获取空集合的总和时,会出现此错误;在求和值之前,您需要确保其为“非空”。因此,问题在于求和?我不能引用“let”这个词。@johnG right,您实际上没有查询,只需在表达式之前添加一个变量。非常感谢您的帮助。因此,我可以得出结论,.count()将在空列表上工作,而Sum()将不工作?@johnG
Sum()
返回与要汇总的列相同的类型,但当转换为SQL时,空查询返回
null
,并且
null
不能映射到
int
。我称之为提供者中的bug。(例如,空集合上的Linq to对象返回0)