问题
When I try to run the following Entity Framework query:
var l = (from s in db.Samples
let action = db.Actions.Where(x => s.SampleID == x.SampleID && x.ActionTypeID == 1).FirstOrDefault()
where s.SampleID == sampleID
select new
{
SampleID = s.SampleID,
SampleDate = action.ActionDate,
}).ToList();
I get following exception:
The cast to value type 'DateTime' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
The problem probably is that Action.ActionDate
is defined as non nullable DateTime
in EF model, but the query returns null
when there are no relevant actions assigned to Sample
.
The workaround is to return a non-anonymous type with nullable properties, but why the anonymous type cannot accept the null result? Can the anonymous type be somehow forced to be created with nullable properties?
回答1:
You are using anonymous types, not generic types. Anonymous types are defined by the compiler at compile time. In the end it's like you created a
class MyEntity
{
public readonly int SampleID;
public readonly DateTime SampleDate;
}
The types are "selected" by the compiler based on the types you use at the right of the =
in the new
. So if SampleID is int
and ActionDate
is DateTime
then those types will be used.
Now, what happens is that when the Entity Framework executes the query and "deserializes" the data in the "MyEntity
" class, it tries to convert the null
it received by the SQL to a DateTime
, and the cast fails. The solution is to define the ActionDate
as a DateTime?
in the anonymous type:
SampleDate = (DateTime?)action.ActionDate,
or to give SampleDate
a value when ActionDate
is null
:
SampleDate = (DateTime?)action.ActionDate ?? default(DateTime),
(this second solution is untested because I don't have an SQL Server near me, if it works SampleDate
will be a DateTime
and will contain the date returned by the query or DateTime.MinValue
when the date is null
)
来源:https://stackoverflow.com/questions/29399001/why-the-anonymous-type-instance-cannot-accept-null-values-returned-by-the-entity