オートマッパーを使用して親クラスをマッピングするのに問題があります。次のクラスを指定して、マッピング プロファイルを作成しました。
マッピング クラス:
public class SourceClass
{
public int SourceProperty1 { get; set; }
public int SourceProperty2 { get; set; }
public string SourceProperty3 { get; set; }
public string SourceProperty4 { get; set; }
}
public class TargetBaseClass
{
public int TargetProperty1 { get; set; }
public int TargetProperty2 { get; set; }
}
public class TargetClass1: TargetBaseClass
{
public string TargetProperty3 { get; set; }
}
public class TargetClass2: TargetBaseClass
{
public string TargetProperty4 { get; set; }
}
地図:
public class MappingProfile: Profile
{
protected override void Configure()
{
CreateMap<SourceClass, TargetBaseClass>()
.Include<SourceClass, TargetClass1>()
.Include<SourceClass, TargetClass2>()
.ForMember(dst => dst.TargetProperty1, opt => opt.MapFrom(src => src.SourceProperty1))
.ForMember(dst => dst.TargetProperty2, opt => opt.MapFrom(src => src.SourceProperty2));
CreateMap<SourceClass, TargetClass1>()
.ForMember(dst => dst.TargetProperty3, opt => opt.MapFrom(src => src.SourceProperty3));
CreateMap<SourceClass, TargetClass2>()
.ForMember(dst => dst.TargetProperty4, opt => opt.MapFrom(src => src.SourceProperty4));
}
}
そして最後に私のプログラム:
static void Main(string[] args)
{
Mapper.Initialize(x => x.AddProfile<MappingProfile>());
var sourceClass = new SourceClass
{
SourceProperty1 = 1,
SourceProperty2 = 2,
SourceProperty3 = "3",
SourceProperty4 = "4"
};
var targetBaseClass = Mapper.Map<TargetBaseClass>(sourceClass);
var targetClass1 = Mapper.Map<TargetClass1>(sourceClass);
var targetClass2 = Mapper.Map<TargetClass2>(sourceClass);
Console.WriteLine("TargetBaseClass: {0} {1}", targetBaseClass.TargetProperty1,
targetBaseClass.TargetProperty2); //1 2
Console.WriteLine("TargetClass1: {0} {1} {2}", targetClass1.TargetProperty1, targetClass1.TargetProperty2,
targetClass1.TargetProperty3);//0 0 3 ???
Console.WriteLine("TargetClass2: {0} {1} {2}", targetClass2.TargetProperty1, targetClass2.TargetProperty2,
targetClass2.TargetProperty4);//1 2 4
}
問題は、派生クラスにマッピングしようとすると、親クラスのプロパティが の場合はマッピングされませんが、 の場合はマッピングさTargetClass1
れることですTargetClass2
。何が間違っているのか、なぜこれら 2 つのマップの動作が異なるのか、誰かに説明してもらえますか? (私が重要な順序はありInclude
ますか?)
編集:よく調べてみると、順序は確かに重要です。ただし、なぜ秒だけInclude
がカウントされるのかはまだわかりません。
Edit2: @GruffBunnyのコメントに基づいて、拡張メソッドを使用してこれを「修正」できると思います。しかし、なぜ彼らがこのようにしたのか、私にはよくわかりません。のコードを見るとAutoMapper.TypeMap
、次のことがはっきりとわかります。
public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType)
{
_includedDerivedTypes[derivedSourceType] = derivedDestinationType;
}
明らかにこれは、含まれるソース タイプごとに 1 つの宛先しか指定できないことを意味します。ただし、複数の宛先タイプをサポートすることを妨げるものは何もありません。