2017-03-09 45 views
0

我需要一些幫助來使用Automapper映射一個匿名對象。目標是在ProductDto中將Product和Unity結合在一起(在此統一體中是產品的屬性)。Automapper:映射一個匿名/動態類型

Autommaper CreateMissingTypeMaps配置設置爲true

我的課表:

public class Product 
{ 
    public int Id { get; set; } 
} 

public class Unity 
{ 
    public int Id { get; set; } 
} 

public class ProductDto 
{ 
    public int Id { get; set; } 
    public UnityDto Unity{ get; set; } 
} 

public class UnityDto 
{ 
    public int Id { get; set; } 
} 

測試代碼

Product p = new Product() { Id = 1 }; 
Unity u = new Unity() { Id = 999 }; 
var a = new { Product = p, Unity = u }; 

var t1 = Mapper.Map<ProductDto>(a.Product); 
var t2 = Mapper.Map<UnityDto>(a.Unity); 
var t3 = Mapper.Map<ProductDto>(a); 

Console.WriteLine(string.Format("ProductId: {0}", t1.Id)); // Print 1 
Console.WriteLine(string.Format("UnityId: {0}", t2.Id)); // Print 999 
Console.WriteLine(string.Format("Anonymous ProductId: {0}", t3.Id)); // Print 0 <<< ERROR: It should be 1 >>> 
Console.WriteLine(string.Format("Anonymous UnityId: {0}", t3.Unity.Id)); // Print 999 

有兩種MAPPS添加到配置文件:

CreateMap<Product, ProductDto>(); 
CreateMap<Unity, UnityDto>(); 
+0

這個答案說在調用Map時傳入設置:http://stackoverflow.com/questions/17085878/automapper-auto-create-createmap,但這是與已知的類型。 – ps2goat

+0

CreateMissingTypeMaps已經在工作。 –

回答

1

問題是如何Automapper地圖匿名對象。我沒有時間去看看Automapper的源代碼,但我得到了我的匿名對象上的細微變化所需的行爲:

var a = new { Id = p.Id, Unity = u }; 

通過這樣做,我甚至可能會刪除以前的映射,因爲現在它僅使用CreateMissingTypeMaps

注意:事實上,我不知道這是否真的是一個問題,或者我只是我的不真實的期望。