問題 状態が無視されるようです。ここに私のシナリオです:Automapperの状態は無視されます
Sourceクラス
public class Source
{
public IEnumerable<Enum1> Prop1{ get; set; }
public IEnumerable<Enum2> Prop2{ get; set; }
public IEnumerable<Enum3> Prop3{ get; set; }
}
バイトから列挙型のサブクラスと[フラグ]が飾られています。宛先クラスには、単に「合計」ビット単位の値を含むEnum1、Enum2、Enum3などのプロパティが含まれています。 EnumerationにEnum1.value !, Enum1.Value2とEnum1.Value3が含まれる場合、目的地にはEnum1.Value1のビット単位の値が含まれます。 Enum1.Value2 |内側のプロパティがnullでなく、マッピングが成功し、正しく目的地を設定する際にEnum1.Value3
先クラス
public Enum1 Prop1 { get; set; }
public Enum2 Prop2 { get; set; }
public Enum3 Prop3 { get; set; }
AutoMapperマッピング
Mapper.CreateMap<Source, Destination>()
.ForMember(m => m.Prop1, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop1.Aggregate((current, next) => current | next));
})
.ForMember(m => m.Prop2, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop2.Aggregate((current, next) => current | next));
})
.ForMember(m => m.Prop3, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop3.Aggregate((current, next) => current | next));
});
マッピングが正常に動作します。ただし、メンバーのソース値がnullの場合(Prop1がnullの場合はマッピングをスキップ)、マッピングをスキップします。
Source.Prop1がnullであることをデバッグから確認できます。条件は完全に無視され、値がnullであることを示す例外が返されます。
Trying to map Source to Destination. Destination property: Prop1. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. --> Value cannot be null. Parameter name: source
私はIsSourceValueNullがPROP1またはnullではない、実際のソースクラスをチェックかはわかりません。メンバProp1のみがnullです。
ヘルプは評価されています。
感謝パトリック。私はこれを分離して全く同じ例外を得る。 – TimJohnson
私は前にそれをやったと思った。おそらく、c.IsSourceValueNullは、マップされるソースオブジェクト全体がnullかどうかを表している可能性があります。私はそれが "c => c.Prop1!= null"でなければならないのだろうか? – PatrickSteele
"条件"を使用してコードサンプルを見つけることができませんでした。ごめんなさい。私はあなたがいつもやることができると思います:o.MapFrom(f => f.Prop1 == null?null:f.Prop1.Aggregate(...)) – PatrickSteele