我在使用AutoMapper时遇到了一个小问题。我已经孤立了我所面临的问题,如果这真的是一个问题,而不仅仅是一个误解的话。
以下是我正在使用的课程:
public class DemoEntity
{
public List<string> Items { get; set; }
public string Name { get; set; }
}
public class DemoDto
{
public List<string> Items { get; set; }
public string Name { get; set; }
}
public class DemoProfile : Profile
{
public DemoProfile()
{
CreateMap<DemoDto, DemoEntity>()
.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
}
}
在依赖项注入部分(它似乎在.NET 6的Program.cs中,但在我的主项目的Startup.cs中(,我读到了以下代码,这些代码应该有助于允许可以为null的集合:
builder.Services.AddAutoMapper(configAction => { configAction.AllowNullCollections = true; }, typeof(Program));
这是我的测试代码:
var dto = new DemoDto();
var entity = new DemoEntity()
{
Items = new List<string>() { "Some existing item" },
Name = "Existing name"
};
// Works as expected
var newEntity = _mapper.Map<DemoEntity>(dto);
// Sets the entity.Items to an empty list
_mapper.Map(dto, entity);
正如您在DemoProfile构造函数中看到的那样,我将条件设置为仅映射ifsrcMember != null
,这适用于Name
属性。使用服务注册中的AllowNullCollections
,我可以映射到具有空列表的新对象(如果没有AllowNullCollections
部分,则为空列表(。
我的预期结果是AutoMapper看到dto.Items
为null,在映射过程中不接触entity.Items
属性,并在列表中保留1个字符串。实际结果是entity.Items
是一个包含0个项目的列表。Name
属性被忽略。
我是不是错过了什么?如何调整代码以使AutoMapper在映射现有目标时忽略为null的列表?
当源的成员(带有数组List(为null或为空时,可以查找PreCondition以阻止来自源的映射。
CreateMap<DemoDto, DemoEntity>()
.ForMember(dest => dest.Items, opt => opt.PreCondition((source, dest) =>
{
return source.Items != null && source.Items.Count > 0;
}))
.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
NET Fiddle 上的示例演示