Skip null values with custom resolver

前端 未结 4 1636
时光取名叫无心
时光取名叫无心 2020-11-29 08:33

I want to use automapper to map between my public data contracts and my DB models. I have created a class which automatically goes through all the contracts are creates mapp

4条回答
  •  暖寄归人
    2020-11-29 09:26

    The solution here works for my project, which is using AutoMapper 6.0.2. In previous projects using AutoMapper 4, I had used IsSourceValueNull to achieve similar behavior. I have nullable types mapped to non-nullable types in my project, this solution is able to handle that scenario.

    I made a small change to the original solution. Instead of checking the type of the property to be mapped, I set the filter in ForAllPropertyMaps to check the type of the source object, so that the custom resolver only applies to maps from that source object. But the filter can be set to anything as needed.

    var config = new MapperConfiguration(cfg =>
    {
        cfg.ForAllPropertyMaps(
            pm => pm.TypeMap.SourceType == typeof(),
            (pm, c) => c.ResolveUsing(new IgnoreNullResolver(), pm.SourceMember.Name));
    });
    
    class IgnoreNullResolver : IMemberValueResolver
    {
        public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
        {
            return sourceMember ?? destinationMember;
        }
    }
    

提交回复
热议问题