c# - 转换为值类型失败,因为物化值为 null

标签 c# entity-framework-6 automapper

我正在使用 AutoMapper 将我的实体投影到模型。

这些是我映射到和映射自的模型:

public partial class Material
{
    public System.Guid Id { get; set; }
    public string Description { get; set; }
    public string EAN { get; set; }

    public virtual InventoryLine InventoryLine { get; set; }
}

public partial class InventoryLine
{
    public System.Guid MaterialId { get; set; }
    public Nullable<decimal> Quantity { get; set; }
    public decimal Price { get; set; }
    public Nullable<System.DateTime> LastInspectionDate { get; set; }
    public int TransactionsSinceLastInspection { get; set; }

    public virtual Material Material { get; set; }
}

public class InventoryLineViewModel
{
    public string EAN { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public decimal? Quantity { get; set; }
    public DateTime? LastInspectionDate { get; set; }
}

我有这个映射:

CreateMap<Material, InventoryLineViewModel>().ForMember(d => d.Price, o => o.MapFrom(s => s.InventoryLine.Price)).ForMember(d => d.Quantity, o => o.MapFrom(s => s.InventoryLine.Quantity)).ForMember(d => d.LastInspectionDate, o => o.MapFrom(s => s.InventoryLine.LastInspectionDate));

每当我运行这段代码时:

Mapper.Initialize(c => { c.AddProfile(new MapperProfile()); });
return context.Material.Include(i => i.InventoryLine).ProjectTo<InventoryLineViewModel>().ToList();

我收到这个错误:

The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

当我映射到和从中映射的所有类型都具有相同的数据类型时,这怎么可能呢?我什至尝试使 Quantity 属性在数据库和 View 模型中不可为空。我仍然遇到同样的错误。

感谢任何帮助:-)

最佳答案

问题是 View 模型 Price 属性类型不可为空,但由于源 InventoryLine 是可选的,EF(如异常消息中所建议的)需要能够在源为 null 时存储可为 null 的值。

您可以通过两种方式修复它:

(A) 使 View 模型属性可为空:

public class InventoryLineViewModel
{
    public decimal? Price { get; set; }
}

(B) 保留 View 模型并更改映射如下:

.ForMember(d => d.Price, o => o.MapFrom(s => ((decimal?)s.InventoryLine.Price) ?? 0))

.ForMember(d => d.Price, o => o.MapFrom(s => s.InventoryLine != null ? s.InventoryLine.Price : 0))

关于c# - 转换为值类型失败,因为物化值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41149772/

相关文章:

c# - Automapper 自定义映射异常

c# - 查找方法的执行时间

visual-studio-2013 - EF6 中 Code First 的逆向工程在哪里找到

c# - EF 同一主键上的多个外键关系

c# - 获取订购组的最后一项

c# - Automapper引用自定义成员映射中现有的子类型映射

c# - 使用 AutoMapper 动态映射包括数组在内的对象

c# - 如何从 C# 中的 Azure HTTP 触发器函数删除 CosmosDB 中的项目

c# - 使用 .NET 检测只读域 Controller ?

c# - 如何使用 Jenkins 安排 C# 单元测试?