2010-12-13 10 views
2

私はこのようなフラットなドメインクラスがある:AutoMapper - 具体的なドメインクラスを継承された宛先DTOクラスにマップする方法

public class ProductDomain 
{ 
    public int ID { get; set; } 

    public string Manufacturer { get; set; } 

    public string Model { get; set; } 

    public string Description { get; set; } 

    public string Price { get; set; } 
} 

私はこのような2つのDTOクラスがあります。

public class ProductInfoDTO 
{ 
    public int ID { get; set; } 

    public string Manufacturer { get; set; } 

    public string Model{ get; set; } 
} 

public class ProductDTO : ProductInfoDTO 
{   
    public string Description { get; set; } 

    public string Price { get; set; } 
} 

を今の問題は次のとおりです。

シナリオ#1:

Mapper.CreateMap<ProductDomain, ProductInfoDTO>() // this mapping works fine 

シナリオ#2:

Mapper.CreateMap<ProductDomain, ProductDTO>() // this mapping is not working and throws System.TypeInitializationException 

私の質問は、ProductDomainとProductDTO(ProductInfoDTOを継承する)間のマッピングを、ソースクラスと宛先クラスの両方の定義を破ることなく作成する方法です。また、ドメインクラスProductDomainの新しい継承を導入したくありません。

おかげ

+0

のようなカスタムのTypeConverterを持つマップを作成することができますあなたのコード。上のコードをプロジェクトにコピー&ペーストしてもうまくいきました。私もサンプルのProductDomainオブジェクトを作成し、問題なくデータをProductDTOにマップしました。 – PatrickSteele

答えて

0

あなたはこの

public class ProductDomainToProductDTOConverter : ITypeConverter<ProductDomain, ProductDTO> 
{ 
    public ProductDTO Convert(ProductDomain source) 
    { 
     ProductDTO product = new ProductDTO(); 
     product.Price = source.Price; 
     ... 

     return product; 
    } 
} 

のように、独自のカスタムのTypeConverterを構築し、で起こっている何か他のものが存在しなければならない。この

Mapper.CreateMap<ProductDomain, ProductDTO>().ConvertUsing<ProductDomainToProductDTOConverter>(); 
関連する問題