繁体   English   中英

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

[英]AutoMapper - how to ignore null fields on the source, while using AutoMapper.Map - sometimes

所以我们有一个情况,我们正在映射,比如说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作为公共“合同”库的一部分,任何外部解决方案都可以使用它来向我们发送数据。 在大多数情况下,当我们想要使用AutoMapperThingDto映射到Thing对象时,一切都很好。 默认情况下, ThingDto上为null的值将“ ThingDtoThing对象上不为null的任何内容。

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

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

任何帮助将不胜感激。

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

请参阅: 在相同的两个对象类型之间创建两个Automapper映射

它可能需要一个包装类来使其更易于维护,但我建议这样的事情:

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);

暂无
暂无

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

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