1
我正在使用AutoMapper将我的实体投影到模型。由于物化值为空导致值类型失败
这些模型I'mm映射和:
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
属性在数据库和视图模型中是不可空的。我仍然得到同样的错误。
任何帮助理解:-)
'Material'和'InventoryLine'之间的关系类型是什么?我的意思是,这是'一对一',但哪一端是必需的,哪一端是可选的。任何流利的配置? –
@IvanStoev物料是必需的,InventoryLine是可选的。没有流利的配置:-) –
也许有点偏离主题,但我认为推荐'valueinjecter'作为您的映射器插件,而不是AutoMapper。 – silkfire