我正在使用 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/