我正在用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。 我該如何解決這個問題?
你可以發佈簡化的類定義,而不是口頭描述?也不清楚什麼是「項目」 –
屬性和PropertySurvey屬性是由項目表示的其他類嗎?或者是PropertySurvey父對象?正如Sergey所說,我們真的需要這裏的類圖... – Maess
我已經放入了簡化類 – arame3333