2016-12-14 3 views
1

AutoMapperを使用してエンティティをモデルに投影しています。実体化された値がnullであるため、キャスト・トゥー・バリュー・タイプが失敗しました

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

I:私はこのコードを実行するたびに

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)); 

:私はこのマッピングを持っている

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; } 
} 

これら

は、にしてからモデルI'mmマッピングされていますこのエラーが発生する:

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プロパティをデータベースとビューモデルでnull不可能にしようとしました。私はまだ同じエラーが発生します。

任意の助けを

+0

'Material'と' InventoryLine'の間の関係のタイプは何ですか?つまり、それは「1対1」ですが、どちらの終わりが必要で、どのオプションが必要ですか。流暢な設定ですか? –

+0

@IvanStoevマテリアルは必須で、InventoryLineはオプションです。いいえ、流暢な設定はありません:-) –

+0

おそらく少し話題ですが、マザープラグインとして 'valueinjecter'を推奨しています。私の正直な意見では、AutoMapperよりはるかに優れています。 – silkfire

答えて

4

:-)理解される問題は、ビューモデルPriceプロパティタイプが非NULL可能であるが、ソースInventoryLineはオプションであるため、EFは(例外メッセージに示唆されるように)できるようにする必要があることですソースがnullの場合はnull値を格納します。

次の2つの方法でそれを修正することができます:

(A)ビューモデルのプロパティのNULL可能にします:

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)) 
関連する問題