繁体   English   中英

从源映射到现有目标时,AutoMapper 不会忽略 List

[英]AutoMapper does not ignore List when mapping from source to existing destination

我对 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 中),我有这段代码,我读过它应该有助于允许可为空的 collections:

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 构造函数中看到的那样,我将条件设置为仅 map if srcMember != null ,这适用于Name属性。 使用服务注册中的AllowNullCollections ,我可以将 map 转换为带有 null 列表的新 object (将是没有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 上的示例演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM