很簡單。您必須分兩步來映射信息。
首先讓我們簡化您的示例:
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);
如果有三級乙等對象,每個對象其中包含四個C對象的列表,您希望映射的結果有多少個A對象? – mjwills
可能的重複[可能使用AutoMapper將一個對象映射到對象列表?](https://stackoverflow.com/questions/18096034/possible-to-use-automapper-to-map-one-object-to-對象列表) –
我不喜歡重複問題中的解釋,所以我試圖解釋它更好一點。我希望我能夠實現這一點,它可以幫助你理解你必須走的路。 –