c# - 为什么匿名类型实例不能接受 Entity Framework 查询返回的空值?

标签 c# entity-framework anonymous-types

当我尝试运行以下 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 并且 ActionDateDateTime,那么将使用这些类型。

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

SampleDate = (DateTime?)action.ActionDate,

或者在 ActionDatenull 时给 SampleDate 一个值:

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

(第二个解决方案未经测试,因为我附近没有 SQL Server,如果它有效,SampleDate 将是一个 DateTime 并将包含返回的日期查询或 DateTime.MinValue 当日期为 null)

关于c# - 为什么匿名类型实例不能接受 Entity Framework 查询返回的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399001/

相关文章:

c# - object[] = object[] f = new object[] 和 var f = new [] 的区别?

c# - DataGridVIew填充了匿名类型,如何过滤?

c# - WPF ContextMenu 单击时消失

c# - WPF Datagrid 显示列两次

c# - 如何将数组作为 Cosmos DB 查询的 SQL 查询参数传递

c# - "Context cannot be used while the model is being created"异常与 ASP.NET 标识

c# - EF 6 关系 : One or more validation errors were detected during model generation

c# - C# 中的循环命名空间

.net - 如何在 Entity Framework 中使用数据库中的默认列值?

c# - 如何在 C# 中将此功能编写为通用扩展方法?