Skip null values with custom resolver

前端 未结 4 1657
时光取名叫无心
时光取名叫无心 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:03

    I've got the same exact issue with mapping up the conditionals to the non-generic types. Here's how I solved it.

    Wire up:

    foreach (PropertyInfo p in type.GetProperties().Where(x => x.GetCustomAttributes().Any()))
        map.ForMember(p.Name, x => x.ResolveUsing(typeof(SkipMapIfNullResolver)).FromMember(p.Name));
    

    The second .FromMember is required so the value for the member is passed to the value resolver, rather than the full model.

    The resolver looks like this:

    public class SkipMapIfNullResolver : IValueResolver
    {
        public ResolutionResult Resolve(ResolutionResult source)
        {
            if (source.Value == null)
                source.ShouldIgnore = true;
    
            return source;
        }
    }
    

提交回复
热议问题