C# AutoMapper-如何在使用AutoMapper.Map时忽略源上的空字段-有时
所以我们有一种情况,我们从C# AutoMapper-如何在使用AutoMapper.Map时忽略源上的空字段-有时,c#,automapper,C#,Automapper,所以我们有一种情况,我们从东西映射到: public class ThingDto { public string FirstName { get; set; } public string LastName { get; set; } public Guid? SomeNiceId { get; set; } } 当然还有——目的站东西: public class Thing { public string FirstName { get; set; }
东西映射到:
public class ThingDto {
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid? SomeNiceId { get; set; }
}
当然还有——目的站东西:
public class Thing {
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid? SomeNiceId { get; set; }
}
以此为背景,以下是我试图解决的情况:
我们将DTO作为公共“合同”库的一部分,任何外部解决方案都可以使用它向我们发送数据。在大多数情况下,当我们想使用AutoMapper
从ThingDto
映射到Thing
对象时,一切都很顺利。默认情况下,ThingDto
上的null
值将“null”掉Thing
对象上的任何非null值
但是,我们需要源成员上的null
值(ThingDto
)不映射到目标对象。我们可以在设置中使用条件
,但问题是我们有时只想这样做。当我们调用AutoMapper.Map(thingDto,thing)时,是否可以设置运行时设置代码>
这似乎对其他人来说也是一个问题——但无论我做什么,我都找不到任何关于它的东西。应该有某种方式告诉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));
}
}
公共类NormalProfile:Profile
{
受保护的覆盖无效配置()
{
base.CreateMap();
}
}
公共类ProfileWithCondition:Profile
{
受保护的覆盖无效配置()
{
base.CreateMap().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);
//某些要包含空映射的代码将调用此
var config=new-MapperConfiguration(cfg=>cfg.AddProfile);
config.CreateMapper.Map(thing);
//在你没有的地方编码,你会这样做
var config=new-MapperConfiguration(cfg=>cfg.AddProfile);
config.CreateMapper.Map(thing);
CreateMap().ForAllMembers(opts=>opts.Condition((src,dest,srcMember)=>srcMember!=null));除非我遗漏了什么,否则上面的注释会使条件每次都有效,而不是只有在询问者请求时才有效。EDI将测试它,看看它是否达到我们需要它做的事情。