2016-12-14 89 views
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属性在数据库和视图模型中是不可空的。我仍然得到同样的错误。

任何帮助理解:-)

+0

'Material'和'InventoryLine'之间的关系类型是什么?我的意思是,这是'一对一',但哪一端是必需的,哪一端是可选的。任何流利的配置? –

+0

@IvanStoev物料是必需的,InventoryLine是可选的。没有流利的配置:-) –

+0

也许有点偏离主题,但我认为推荐'valueinjecter'作为您的映射器插件,而不是AutoMapper。 – silkfire

回答

4

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

您可以通过两种方式解决这个问题:

(A)使视图模型属性为空的:

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

(B)保持视图模型和修改映射如下:

.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)) 
相关问题