AutoMapperを使用して、エンティティをDTOにマッピングしています。私のエンティティの中には、派生したエンティティによってオーバーライドされる仮想プロパティがあります。私は定義されている基本クラスを使って仮想プロパティをマッピングしています。しかし、派生クラスをマッピングするとき、AutoMapperはオーバーライドされたクラスの代わりに仮想プロパティの基本実装をマッピングします。AutoMapperを使用してプロパティをオーバーライドする派生クラスごとに仮想プロパティを明示的にマッピングせずにマップする方法はありますか?
私はクラス定義から始めましょう:
public class BaseType
{
public virtual string Title
{
get { return string.Empty; }
}
}
public class DerivedType : BaseType
{
public override string Title
{
get { return Name; }
}
public string Name { get; set; }
}
public class BaseTypeDto
{
public string Title { get; set; }
}
public class DerivedTypeDto : BaseTypeDto
{
public string Name { get; set; }
}
今マッピング設定のために:
CreateMap<BaseType, BaseTypeDto>()
.ForMember(n => n.Title, p => p.MapFrom(q => q.Title ?? "-"))
.Include<DerivedType, DerivedTypeDto>();
CreateMap<DerivedType, DerivedTypeDto>()
そして最後にマッピング:
DerivedTypeDto dto = Mapper.Map<DerivedType, DerivedTypeDto>(instance);
私はタイトルを入れたとき派生型を構成するCreateMap呼び出しでのマッピング。しかし、私は20種類の派生型を持っているので、派生クラスごとに繰り返す必要はなく、基本クラスでTitleマッピングを構成したいと思っています。
これはAutoMapperで可能ですか?