2017-08-26 56 views
0

我想映射包含源類的對象數組,它必須被映射的目標類。地圖數組的列表使用自動映射器

class A 
{ 
     public string Id { get; set; } 
     public string Name { get; set; } 
     public string Url { get; set; } 
     public string Details { get; set; } 
     public string Image { get; set; } 
     public string Decription{ get; set;} 
} 

class B 
{ 
public string Id { get; set; } 
public string Name { get; set; } 
public List<C> { get; set; } 
} 

class C{ 
    public string Url { get; set; } 
    public string Details { get; set; } 
    public string Image { get; set; } 
    public string Decription{ get; set;} 
} 

我需要從B級的映射表使用自動映射器 列出A類請幫助

+0

如果有三級乙等對象,每個對象其中包含四個C對象的列表,您希望映射的結果有多少個A對象? – mjwills

+1

可能的重複[可能使用AutoMapper將一個對象映射到對象列表?](https://stackoverflow.com/questions/18096034/possible-to-use-automapper-to-map-one-object-to-對象列表) –

+0

我不喜歡重複問題中的解釋,所以我試圖解釋它更好一點。我希望我能夠實現這一點,它可以幫助你理解你必須走的路。 –

回答

2

很簡單。您必須分兩步來映射信息。

首先讓我們簡化您的示例:

class A { 
    public string AttrB { get; set; } 
    public string AttrC { get; set; } 
} 
class B { 
    public string AttrB { get; set; } 
} 

class C { 
    public string AttrC { get; set;} 
} 

從b創建A的一個對象和C,你必須創建兩個地圖後對方使用它們:

Mapper.CreateMap<B, A>(); 
Mapper.CreateMap<C, A>(); 

var c = new C { AttrC = "AttrCValue" }; 
var b = new B { AttrB = "AttrBValue" }; 
var a = Mapper.Map<A>(b); // a with the attribute values of b 
Mapper.Map(c, a); // map the attribute values of c also into a 

我覺得沒有什麼新的爲你。但現在來了棘手的部分。它的工作原理相同的原理:

class A { 
    public string AttrB { get; set; } 
    public string AttrC { get; set; } 
} 
class B { 
    public string AttrB { get; set; } 
    public List<C> AttrBList { get; set; } 
} 

class C { 
    public string AttrC { get; set;} 
} 

我們需要另一個地圖和一個自定義轉換器:

Mapper.CreateMap<B, A>(); 
Mapper.CreateMap<C, A>(); 
Mapper.CreateMap<B, IEnumerable<A>>().ConvertUsing<BConverter>(); 

class BConverter : ITypeConverter<B, IEnumerable<A>> { 
    public IEnumerable<A> Convert(ResulutionContext ctx) { 
     B b = (B)ctx.SourceValue; 
     foreach(var aFromC in b.AttrBList.Select(c => Mapper.Map<A>(c))) { // map c attributes into an a object and return it (through Select it's a mapping for all items of the list AttrBList) 
      Mapper.Map(b, aFromC); // push the attribute values from b to the aFromC object. Because this is inside the loop, it happens for every Item in the AttrBList array 
      yield return aFromC; 
     } 
    } 
} 

現在你可以使用它:

var allAObjects = Mapper.Map<IEnumerable<A>>(listOfBObjects);