所以我们有一种情况,我们从比方说 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 作为公共(public)“契约(Contract)”库的一部分,任何外部解决方案都可以使用它来向我们发送数据。大多数情况下,当我们想使用AutoMapper
从 ThingDto
映射到 Thing
对象,一切都是桃色的。默认情况下,值为 null
在 ThingDto
上将“清除”Thing
上不为空的任何内容对象。
但是,我们有一种情况需要 null
源成员(ThingDto
)上的值只是没有映射到目标 Thing
目的。我们可以用 Condition
来做到这一点在设置中,但问题是我们只想有时这样做。当我们调用 AutoMapper.Map<ThingDto, Thing>(thingDto, thing);
时,是否可以设置运行时设置? ?
这似乎对其他人来说也是一个问题 - 但无论我做什么,我都找不到任何关于它的东西。应该有某种方式来告诉AutoMapper
即时我们不想映射空值,但我一无所获。
如有任何帮助,我们将不胜感激。
最佳答案
您是否考虑过为相同类型设置多个 AutoMapper 配置文件,一个包含条件,一个不包含条件,然后实例化当时有效的配置?
参见: 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);
关于c# - AutoMapper - 如何在使用 AutoMapper.Map 时忽略源上的空字段 - 有时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679663/