2012-04-04 141 views
4

我需要將單個固定大小的數組映射到多個屬性。 例如給出這個類:如何使用AutoMapper將數組映射到多個屬性?

public class Source 
{ 
    public int[] ItemArray{get;set} // always 4 items 
} 

我想數組映射到這個類

public class Dest 
{ 
    public int Item1{get;set;} 
    public int Item1{get;set;} 
    public int Item1{get;set;} 
    public int Item1{get;set;} 
} 

有一個簡單的方法與AutoMapper做(而不實際映射每個單獨的現場)?

回答

5

爲目的地的屬性創建映射:

Mapper.CreateMap<Source, Dest>() 
    .ForMember(d => d.Item1, o => o.MapFrom(s => s.ItemArray[0])) 
    .ForMember(d => d.Item2, o => o.MapFrom(s => s.ItemArray[1])) 
    .ForMember(d => d.Item3, o => o.MapFrom(s => s.ItemArray[2])) 
    .ForMember(d => d.Item4, o => o.MapFrom(s => s.ItemArray[3])); 

用法:

Source source = new Source() { ItemArray = new int[] { 1, 2, 3, 4 } }; 
Dest dest = Mapper.Map<Source, Dest>(source); 

UPDATE:沒有,有沒有簡單的方法。 AutoMapper如何理解,你的屬性Foo應該被映射到源屬性Bar中的索引N處的元素?你應該提供所有這些信息。

UPDATE:從Automapper

投影變換源到目的地以外平坦化對象模型。如果沒有額外的配置,AutoMapper需要一個平坦的目的地來匹配源類型的命名結構。如果要將源值映射到與源結構不完全匹配的目標,則必須指定自定義成員映射定義。

所以,是的。如果命名結構不匹配,則必須爲成員指定自定義映射。

UPDATE: 嗯,其實你可以手動執行所有轉換(但我不認爲這是更好的方法,特別是如果你有可能通過名稱映射其他屬性):

Mapper.CreateMap<Source, Dest>().ConstructUsing((s) => new Dest() 
{ 
    Item1 = s.ItemArray[0], 
    Item2 = s.ItemArray[1], 
    Item3 = s.ItemArray[2], 
    Item4 = s.ItemArray[3] 
} 
+0

所以基本上沒有... – 2012-04-04 17:18:08

+0

@Dror Helper是的,看到我最後一次更新automapper wiki的報價。 – 2012-04-04 17:27:19

+0

是的 - 但有一些技巧,如自定義轉換器和其他設施,也許其中一個將幫助 – 2012-04-04 17:34:10

相關問題