【发布时间】:2023-03-03 21:04:01
【问题描述】:
我在使用 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 中),我读过的这段代码应该有助于允许可空集合:
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 构造函数中看到的那样,我将条件设置为仅在 srcMember != null 时进行映射,这适用于 Name 属性。使用服务注册中的 AllowNullCollections,我可以映射到具有空列表的新对象(如果没有 AllowNullCollections 部分,它将是一个空列表)。
我的预期结果是 AutoMapper 会看到 dto.Items 为空,并且在映射期间不触及 entity.Items 属性,并在列表中保留 1 个字符串。实际结果是 entity.Items 是一个包含 0 个项目的列表。名称属性被忽略。
我错过了什么吗?如何调整我的代码以使 AutoMapper 在映射现有目的地时忽略一个为空的列表?
【问题讨论】:
标签: c# .net automapper