今天使用LINQ to Entities时出现了一个错误,为方便说明创建了个Demo表用于还原问题:
create table Person
(
Id int identity(1,1) primary key,
Name nvarchar(20) not null,
Age int not null
)
insert into Person select 'person1',20
insert into Person select 'person2',30
insert into Person select 'person3',40
LINQ to Entities相关程序:
var context = new testContext();
var data = context.People
.GroupBy(item => item.Name)
.Select(item => new { item.FirstOrDefault().Name, Age = item.Where(item2 => item2.Age >= 30).Sum(item2 => item2.Age) });
foreach (var item in data)
{
Console.WriteLine("{0},{1}", item.Name, item.Age);
}
程序执行出错,错误信息如下:
引用内容
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
在SQL Server Profiler获取了对应SQL语句:
Select
1 AS [C1],
[Project4].[C1] AS [C2],
[Project4].[C2] AS [C3]
FROM ( Select
[Project3].[C1] AS [C1],
(Select
SUM([Extent3].[Age]) AS [A1]
FROM [dbo].[Person] AS [Extent3]
Where ([Project3].[Name] = [Extent3].[Name]) AND ([Extent3].[Age] >= 30)) AS [C2]
FROM ( Select
[Distinct1].[Name] AS [Name],
(Select TOP (1)
[Extent2].[Name] AS [Name]
FROM [dbo].[Person] AS [Extent2]
Where [Distinct1].[Name] = [Extent2].[Name]) AS [C1]
FROM ( Select DISTINCT
[Extent1].[Name] AS [Name]
FROM [dbo].[Person] AS [Extent1]
) AS [Distinct1]
) AS [Project3]
) AS [Project4]
查询得到的记录集:
1 person1 NULL
1 person2 30
1 person3 40
所以,问题的原因是Where(item2 => item2.Age >= 30)导致了查询结果存在NULL值,在尝试将它转换成System.Int32时出了错,解决方法如下:
var data = context.People
.GroupBy(item => item.Name)
.Select(item => new { item.FirstOrDefault().Name, Age = item.Where(item2 => item2.Age >= 30).Sum(item2 => (int?)item2.Age) ?? 0 });
我的博物馆故事 官方安卓版v1.61.2
我的博物馆故事是一款以消除为主题的经营养成类手游,在这里玩家
专业模拟飞行10 手机版v12.2.4
专业模拟飞行10安卓版是一款飞行休闲手游,顶尖的物理飞行引擎
动物起义战斗模拟器二琳同款 最新版v4.1.1
动物起义战斗模拟器是一个非常有趣的模拟类游戏,玩家可以召唤各
迷你世界七周年 安卓手机版v1.43.0
迷你世界7周年是一款由《迷你世界》官方推出的庆祝特别版本,在
劫后公司无限资源版 v1.0.5.1
劫后公司内置菜单版是游戏的破解版本,在该版本中为玩家提供了内