AutoMapper skip all members on source that are null

ぃ、小莉子 提交于 2021-01-27 23:04:10

问题


given this mapping

_mapper.Map(personDto, person, opt => opt.ConfigureMap()
    .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null))
);

person before mapping

FirstName: "John"
LastName: "Doe"
Email: "John.Doe@gmail.com"

personDto before mapping

FirstName: "Jim"
LastName: "Denver"
Email: NULL

expected output person

FirstName: "Jim"
LastName: "Denver"
Email: "John.Doe@gmail.com"

actual output person

FirstName: "Jim"
LastName: "Denver"
Email: NULL

mapper came from this post https://stackoverflow.com/a/43947731/3511012


Update, I also tried using ResolveUsing and it has the same output

_mapper.Map(personUpdateDto, person, opt => opt.ConfigureMap()
    .ForAllOtherMembers(opts => opts.ResolveUsing((src, dest, srcMember, dstMember) => srcMember ?? dstMember))
);


回答1:


If I understand correctly then you have a predefined mapping from PersonDto to Person and trying to configure that mapping in the Map method. In that case, the code below really doesn't work as you want because the lambda in the ForAllMembers is never being called.

var config = new MapperConfiguration(cfg => cfg.CreateMap<PersonDto, Person>());//.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)));
var mapper = config.CreateMapper();
var person = new Person { FirstName = "John", LastName = "Snow" ,Email="test@mail.com"};
var personUpdateDto = new PersonDto { FirstName = "Jim", LastName = "Denver" };
var a = mapper.Map(personUpdateDto, person, opt => opt.ConfigureMap()
            .ForAllMembers(opts => opts.Condition((src, dest, srcMember) =>
            {
                return srcMember != null;
            }
            )));

But the code below works as you want:

var config = new MapperConfiguration(cfg => cfg.CreateMap<PersonDto, Person>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)));
var mapper = config.CreateMapper();
var person = new Person { FirstName = "John", LastName = "Snow", Email = "test@mail.com" };
var personUpdateDto = new PersonDto { FirstName = "Jim", LastName = "Denver" };
var a = mapper.Map(personUpdateDto, person);

Another way to work with inline maps is to define empty mapper configuration and then add inline maps:

var config = new MapperConfiguration(cfg => { });
var mapper = config.CreateMapper();
var person = new Person { FirstName = "John", LastName = "Snow", Email = "test@mail.com" };
var personUpdateDto = new PersonDto { FirstName = "Jim", LastName = "Denver" };
var a = mapper.Map(personUpdateDto, person,opts=>opts.ConfigureMap()
.ForAllMembers(opts2 => opts2.Condition((src, dest, srcMember) =>
{
    return srcMember != null;
}
)));


来源:https://stackoverflow.com/questions/54677087/automapper-skip-all-members-on-source-that-are-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!