嵌套集合在AutoMapper 5.1中不工作

本文关键字:工作 集合 AutoMapper 嵌套 | 更新日期: 2023-09-27 18:17:48

尝试从v4.2升级到AutoMapper 5.1,并发现一个集合在运行时没有映射-源对象在集合中有项,但映射的目标属性为空。

在4.2中,使用相同的映射配置(除了MemberList),一切都完全按照预期工作。CreateMap()函数

我有这样的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>();
}

And Mapping confirmation like so

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的Counties集合为空(一个包含0项的列表),尽管源对象的.Counties集合中有项:

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

任何线索将不胜感激!

嵌套集合在AutoMapper 5.1中不工作

经过一番挖掘,发现AutoMapper 5升级引入了一些突破性的变化。具体来说,在像我这样的目标集合有getter但没有setter的情况下,行为已经改变了。在AutoMapper 4中,默认行为是默认使用destination属性,而不是尝试创建一个新实例。默认情况下,AutoMapper 5不会这样做。

解决方案是告诉AutoMapper显式地使用目标值:

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

我相信有一个很好的理由来引入这样一个破坏性的改变,但是当你已经实现了一个广泛的模式,现在必须寻找和修复每个可能受此变化影响的映射对象时,它会导致无休止的心痛。

我几乎想放弃升级并坚持使用Automapper 4.2,因为它完全满足了我的需求,而不需要大量额外和不必要的配置。

详情请参阅https://github.com/AutoMapper/AutoMapper/issues/1599