2016-11-14 69 views
0

嘗試從v4.2升級到AutoMapper 5.1,並發現集合在運行時未映射 - 源對象在集合中有項目,但映射的目標屬性爲空。嵌套集合在AutoMapper 5.1中無效

在4.2,一切工作完全一樣使用相同的映射配置預期(保存在CreateMap()構造函數的MemberList.None)

我的DTO像這樣

public class GeographicEntity 
{ 
... 
} 

public class County : GeographicEntity 
{ 
    ... 
} 

public class State : GeographicEntity 
{ 
    public List<County> Counties { get; } = new List<County>(); 
} 

而且喜歡的ViewModels所以

public class GeographicEntityViewModel 
{ 
    ... 
} 

public class CountyViewModel : GeographicEntityViewModel 
{ 
    ... 
} 

public class StateViewModel : GeographicEntityViewModel 
{ 
    public List<CountyViewModel> Counties { get; } = new List<CountyViewModel>(); 
} 

與地圖確認,像這樣

Mapper.Initialize(configuration => 
{ 
    configuration.CreateMap<GeographicEntity, GeographicEntityViewModel>(MemberList.None); 

    configuration.CreateMap<County, CountyViewModel>(MemberList.None) 
    .IncludeBase<GeographicEntity, GeographicEntityViewModel>(); 

    configuration.CreateMap<State, StateViewModel>(MemberList.None) 
    .IncludeBase<GeographicEntity, GeographicEntityViewModel>(); 
}); 

的Mapper.Map <>呼叫後,StateViewModel的縣集合爲空(0項的列表),即使源對象有其.Counties集合中的項目:

var st = new State() 
... (initialize the state, including the .Counties list) 
var stateViewModel = Mapper.Map<StateViewModel>(st); 

任何線索將不勝感激!

回答

0

經過一番挖掘,事實證明,AutoMapper 5升級引入了一些重大變化。具體來說,在目標集合有吸氣但沒有設置者的情況下,行爲發生了變化。在AutoMapper 4中,默認行爲是默認使用destination屬性,而不是嘗試創建新實例。 AutoMapper 5默認不會這樣做。

的解決方法是告訴AutoMapper使用明確的目的地值:

.ForMember(dest => dest.Counties, o => o.UseDestinationValue()) 

我敢肯定有一個很好的理由,引入這樣一個重大更改,但它會導致沒有心痛的結束,當你」已經實施了一個廣泛的模式,現在不得不尋找並修復每個可能受此變化影響的映射對象。

我幾乎想要升級並堅持使用Automapper 4.2,因爲它完全符合我的需求,而無需額外和不必要的大量配置。

有關更多詳細信息,請參閱https://github.com/AutoMapper/AutoMapper/issues/1599