2010-12-13 81 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; } 
} 

我有兩個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

您的自定義類型轉換器必須有東西在別的事情上你的代碼。我複製/粘貼上面的代碼到一個項目,它運行得很好。我甚至創建了一個示例ProductDomain對象,它將數據映射到ProductDTO,沒有任何問題。 – PatrickSteele 2010-12-13 13:59:36

回答

0

你可以建立自己的自定義類型轉換器這樣

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

     return product; 
    } 
} 

,然後創建一個映射,像這樣

Mapper.CreateMap<ProductDomain, ProductDTO>().ConvertUsing<ProductDomainToProductDTOConverter>(); 
相關問題