[英]Automapper 10 wouldn't map collection properties when setting MaxDepth to 1
Properties of type ICollection are not mapped when migrating from Automapper 9 to 10. I am using .NET 5.从 Automapper 9 迁移到 10 时,未映射 ICollection 类型的属性。我使用的是 .NET 5。
I have the following setup:我有以下设置:
private class Class1
{
public int Id { get; set; }
}
private class Class2
{
public int Id { get; set; }
public ICollection<Class1> ChildClasses { get; set; }
}
private class Class2Bis
{
public int Id { get; set; }
public ICollection<Class1> ChildClasses { get; set; }
}
private class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Class2, Class2Bis>().ReverseMap();
}
}
I am injecting the mapper using a helper method that uses AutoMapper.Extensions.Microsoft.DependencyInjection module:我正在使用使用 AutoMapper.Extensions.Microsoft.DependencyInjection 模块的辅助方法注入映射器:
public static IServiceCollection AddMapper(this IServiceCollection services, params Assembly[] assemblies)
{
return services.AddAutoMapper(cfg =>
{
cfg.ForAllMaps((map, exp) => exp.MaxDepth(1));
cfg.AllowNullCollections = true;
cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
},
assemblies);
}
The following test succeeds using Automapper 9 but fails using Automapper 10:以下测试使用 Automapper 9 成功,但使用 Automapper 10 失败:
[Fact]
public void Should_Map_ClassesWithCollectionProperties()
{
var object2 = new Class2
{
Id = 1,
ChildClasses = new List<Class1>()
{
new Class1
{
Id = 1
}
}
};
var object2Bis = _mapper.Map<Class2Bis>(object2);
Assert.Equal(object2.ChildClasses.Count, object2Bis.ChildClasses.Count);
}
object2Bis has an empty ChildClasses property when using Automapper 10.使用 Automapper 10 时,object2Bis 的 ChildClasses 属性为空。
Removing cfg.ForAllMaps((map, exp) => exp.MaxDepth(1));
删除cfg.ForAllMaps((map, exp) => exp.MaxDepth(1));
or setting MaxDepth
to 2 (or higher number) makes the code work for me.或将MaxDepth
设置为 2(或更高的数字)使代码对我有用。 There is next note in the 10.0 Upgrade Guide : 10.0 升级指南中有下一条说明:
When reaching
MaxDepth
, destination collections are null/empty, they used to contain null values.到达MaxDepth
时,目的地 collections 为空/空,它们曾经包含 null 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.