An error occurred while using LINQ to Entities today to facilitate the description of creating a demo table for restoring problems:
CREATE TABLE Person
(
Id int Identity (1,1) primary key,
Name nvarchar is 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 related programs:
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 program performed an error with the following error message:
Reference content
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.
The corresponding SQL statement was obtained in SQL Server Profiler:
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] >=) 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]
Query-obtained recordset:
1 Person1 NULL
1 Person2 30
1 Person3 40
So, the cause of the problem is where (item2 => item2). Age >= 30 results in a null value for the query result and an error occurred while trying to convert it to System.Int32, as follows:
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});