2015-12-14 287 views
4

我正在用Automapper語法掙扎。 我有一個PropertySurveys的列表,每個包含1個屬性。 我希望將集合中的每個項目映射到組合這兩個類的新對象。Automapper:如何映射嵌套對象?

所以我的代碼看起來像;

  var propertySurveys = new List<PropertyToSurveyOutput >(); 
      foreach (var item in items) 
      { 
       Mapper.CreateMap<Property, PropertyToSurveyOutput >(); 
       var property = Mapper.Map<PropertyToSurvey>(item.Property); 
       Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput >(); 
       property = Mapper.Map<PropertyToSurvey>(item); 
       propertySurveys.Add(property); 
      } 

我的簡化類看起來像;

public class Property 
{ 
    public string PropertyName { get; set; } 
} 

public class PropertySurvey 
{ 
    public string PropertySurveyName { get; set; } 
    public Property Property { get; set;} 
} 

public class PropertyToSurveyOutput 
{ 
    public string PropertyName { get; set; } 
    public string PropertySurveyName { get; set; } 
} 

所以在PropertyToSurveyOutput對象中,第一個映射PropertyName被設置後。然後設置PropertySurveyName的第二個映射後,但PropertyName被覆蓋爲null。 我該如何解決這個問題?

+1

你可以發佈簡化的類定義,而不是口頭描述?也不清楚什麼是「項目」 –

+0

屬性和PropertySurvey屬性是由項目表示的其他類嗎?或者是PropertySurvey父對象?正如Sergey所說,我們真的需要這裏的類圖... – Maess

+0

我已經放入了簡化類 – arame3333

回答

4

首先,Automapper支持集合的映射。您不需要在循環中映射每個項目。

第二 - 每次需要映射單個對象時,都不需要重新創建映射。將映射創建映射到應用程序啓動代碼(或者在第一次使用映射之前)。

而在去年 - 與Automapper您可以創建映射和定義瞭如何進行自定義地圖的一些屬性:

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>() 
    .ForMember(pts => pts.PropertyName, opt => opt.MapFrom(ps => ps.Property.PropertyName)); 

用法:

var items = new List<PropertySurvey> 
{ 
    new PropertySurvey { 
      PropertySurveyName = "Foo", 
      Property = new Property { PropertyName = "X" } }, 
    new PropertySurvey { 
      PropertySurveyName = "Bar", 
      Property = new Property { PropertyName = "Y" } } 
}; 

var propertySurveys = Mapper.Map<List<PropertyToSurveyOutput>>(items); 

結果:

[ 
    { 
    "PropertyName": "X", 
    "PropertySurveyName": "Foo" 
    }, 
    { 
    "PropertyName": "Y", 
    "PropertySurveyName": "Bar" 
    } 
] 

更新:如果你的Property類有很多屬性,你可以定義兩個默認的映射 - 一個從Property

Mapper.CreateMap<Property, PropertyToSurveyOutput>(); 

,一個來自PropertySurvey。並使用第一映射你PropertySurvey使用映射後:

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>() 
     .AfterMap((ps, pst) => Mapper.Map(ps.Property, pst)); 
+0

我指定的類已經過簡化。如果屬性中有10個字段我想映射到PropertyToSurveyOutput,是否必須指定每個字段,即使字段的名稱是相同的? – arame3333

+0

@ arame3333答案已更新。如果您需要將兩個複雜對象映射到一個對象中,則需要兩個映射 - 一個來自Property,另一個來自PropertySurvey –

+1

非常好,正是我期待的! – arame3333

0

automapper屬性名的第一條規則應該是相同的,然後只將正確地映射和分配的價值,但在你的情況下,一個屬性名稱是唯一的「財產」和第二個屬性名是「PropertyName」,所以使屬性名稱相同,它會爲你工作