簡體   English   中英

嵌套的集合在AutoMapper 5.1中不起作用

[英]Nested Collections Not Working in AutoMapper 5.1

試圖從v4.2升級到AutoMapper 5.1,發現集合在運行時沒有映射-源對象在集合中有項目,但是映射的目標屬性為空。

在4.2下,在相同的映射配置下,一切都按預期工作(在MemberMap中保存,但在CreateMap()ctor中沒有)

我有像這樣的DTO

public class GeographicEntity
{
 ...
}

public class County : GeographicEntity
{
    ...
}

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

像這樣的視圖模型

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 <>之后,即使源對象的.Counties集合中有項目,StateViewModel的Counties集合也為空(包含0項的列表):

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

任何線索將不勝感激!

經過一番挖掘,結果發現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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM