为什么匿名类型实例不能接受 entity framework 查询返回的空值?

Why the anonymous type instance cannot accept null values returned by the entity framework query?

当我尝试 运行 以下 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 模型中被定义为不可空 DateTime,但是查询 returns null 当没有分配相关操作时至 Sample.

解决方法是return一个具有可为空属性的非匿名类型,但为什么匿名类型不能接受空结果?可以以某种方式强制使用可为空的属性创建匿名类型吗?

您使用的是匿名类型,而不是泛型类型。匿名类型由编译器在编译时定义。最后就像你创建了一个

class MyEntity
{
    public readonly int SampleID;
    public readonly DateTime SampleDate;
}

编译器根据您在 new= 右侧使用的类型 "selected" 类型。因此,如果 SampleID 是 int 并且 ActionDateDateTime,那么将使用这些类型。

现在,当 Entity Framework 执行查询和 "deserializes" “MyEntity” class 中的数据时,它会尝试将 class 转换为 null 它由 SQL 接收到 DateTime,并且转换失败。解决方案是将ActionDate定义为匿名类型中的DateTime?

SampleDate = (DateTime?)action.ActionDate,

或当 ActionDatenull 时给 SampleDate 一个值:

SampleDate = (DateTime?)action.ActionDate ?? default(DateTime),

(第二个解决方案未经测试,因为我附近没有 SQL 服务器,如果有效,SampleDate 将是 DateTime 并将包含返回的日期日期为 null)

时的查询或 DateTime.MinValue