AutoMapper-在使用AutoMapper.Map时如何忽略源中的空字段-有时

时间:2019-02-13 21:24:41

标签: c# automapper

所以我们有一种情况,我们从ThingDto开始映射:

public class ThingDto {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid? SomeNiceId { get; set; }
}

当然还有目标站Thing

public class Thing {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid? SomeNiceId { get; set; }
}

以此为背景,这是我要解决的情况: 我们将DTO作为公共“合同”库的一部分,任何外部解决方案都可以使用DTO向我们发送数据。在大多数情况下,当我们要使用AutoMapperThingDto映射到Thing对象时,一切都是桃花心的。默认情况下,null上的ThingDto值将“清空” Thing对象上不为空的任何内容。

但是,在这种情况下,我们需要源成员(null)上的ThingDto值只是不映射到目标Thing对象。我们可以在设置中使用Condition来完成此操作,但是问题是我们只想有时 这样做。调用AutoMapper.Map<ThingDto, Thing>(thingDto, thing);时可以设置运行时设置吗?

对于其他人来说,这似乎也是一个问题-但无论我做什么,我都找不到任何东西。应该有某种方式可以随时告诉AutoMapper我们不想映射空值,但是我什么也没想。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您是否考虑过为同一类型设置多个AutoMapper配置文件,其中一个包含Condition,一个不包含Condition,然后实例化当时有效的配置?

请参阅: Create two Automapper maps between the same two object types

可能需要一个包装器类才能使其更易于维护,但我建议使用类似的方法:

public class NormalProfile : Profile
{
    protected override void Configure()
    {
        base.CreateMap<ThingDto, Thing>();
    }
}

public class ProfileWithCondition : Profile
{
    protected override void Configure()
    {
        base.CreateMap<ThingDto, Thing>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
    }
}

以及用法:

// Some code where you want to include NULL mappings would call this
var config = new MapperConfiguration(cfg => cfg.AddProfile<NormalProfile>);
config.CreateMapper.Map<ThingDto, Thing>(thing);

// Code where you don't, would do this
var config = new MapperConfiguration(cfg => cfg.AddProfile<ProfileWithCondition>);
config.CreateMapper.Map<ThingDto, Thing>(thing);