2013-10-26 47 views
0
class SomeObject 
{ 
    public string name {get;set;} 
} 

class CustomCollection : List<SomeObject> 
{ 
    public int x {get;set;} 
    public string z {get;set;} 
} 

class A 
{ 
    public CustomCollection collection { get ; set; } 
} 

class B 
{ 
    public CustomCollection collection { get ; set; } 
} 


// Creating mapping 
Mapper.CreateMap<A, B>(); 

當我地圖A到B,所有屬性得到正確映射除了X和Z CustomCollection的自定義列表的所有屬性。AutoMapper包括<T>

CustomCollection正確獲取初始化的SomeObject的List,並且SomeObject.Name也正確映射。

只有我在集合中聲明的自定義屬性X,Z沒有被映射。

我在做什麼錯?

我發現的唯一方法就是像下面這樣做映射之後,但它有點挫敗了使用automapper的目的,每當我向CustomCollection添加一個新屬性時它都會中斷。

Mapper.CreateMap<A, B>().AfterMap((source, destination) => { 
    source.x = destination.x; 
    source.z = destination.z ; 
}); 

回答

0

您當前的映射配置不創建一個新的CustomCollectionSomeObject裏面的物品是到源集合中的對象的引用。如果這不是一個問題,你可以使用下面的映射配置:

CreateMap<CustomCollection, CustomCollection>() 
    .AfterMap((source, dest) => dest.AddRange(source)); 

CreateMap<A, B>(); 

如果您還罰款b.collection引用到a.collection你可以使用下面的映射配置:

CreateMap<CustomCollection, CustomCollection>() 
    .ConstructUsing(col => col); 

CreateMap<A, B>(); 

AutoMapper是不適合克隆所以如果你需要,你必須爲此編寫自己的邏輯。

+0

我的問題是,如果SomeObject沒有被初始化或是引用,但是CustomCollection.x和CustomCollection.y沒有被映射,它們分別保持爲0和null。 – newbie

+0

@newbie你有沒有試過我的答案? –