当我尝试运行以下 Entity Framework 查询时:
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();
我得到以下异常:
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.
问题可能是 Action.ActionDate
在 EF 模型中定义为不可为 null 的 DateTime
,但查询返回 null
时没有分配给 Sample
的相关操作。
解决方法是返回一个具有可为空属性的非匿名类型,但为什么匿名类型不能接受空结果呢?可以以某种方式强制使用可为空的属性创建匿名类型吗?
最佳答案
您使用的是匿名类型,而不是通用类型。匿名类型由编译器在编译时定义。最后就像你创建了一个
class MyEntity
{
public readonly int SampleID;
public readonly DateTime SampleDate;
}
编译器根据您在 new
中 =
右侧使用的类型“选择”类型。因此,如果 SampleID 是 int
并且 ActionDate
是 DateTime
,那么将使用这些类型。
现在,当 Entity Framework 执行查询并“反序列化”“MyEntity
”类中的数据时,它会尝试将 null
转换为它由 SQL 接收到 DateTime
,并且转换失败。解决方案是将 ActionDate
定义为匿名类型的 DateTime?
:
SampleDate = (DateTime?)action.ActionDate,
或者在 ActionDate
为 null
时给 SampleDate
一个值:
SampleDate = (DateTime?)action.ActionDate ?? default(DateTime),
(第二个解决方案未经测试,因为我附近没有 SQL Server,如果它有效,SampleDate
将是一个 DateTime
并将包含返回的日期查询或 DateTime.MinValue
当日期为 null
)
关于c# - 为什么匿名类型实例不能接受 Entity Framework 查询返回的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399001/