AutoMapper Map If Not Null, Otherwise Custom Convert

前端 未结 4 1135
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 08:29

Here\'s my code:

Mapper.CreateMap()
   .ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new BarViewModel() : sr         


        
相关标签:
4条回答
  • 2021-02-02 08:49

    You can use custom value resolver. The following should work:

    Mapper.CreateMap<Foo, Foo2>()
       .ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map<Bar,Bar2>(src.Bar)))
    
    0 讨论(0)
  • 2021-02-02 09:03

    Now you can use .NullSubstitute() to replace NULL value to some custom value in Automapper, e.g.:

    CreateMap<SMModel, VM_SMModel>()
                        .ForMember(d => d.myDate, o => o.NullSubstitute(new DateTime(2017,12,12)));
    
    0 讨论(0)
  • 2021-02-02 09:04

    As of Automapper 8, ResolveUsing is no longer an option but inline Func's, IValueResolver and IMemberValueResolver are

    0 讨论(0)
  • 2021-02-02 09:08

    I don't get a compiler error for the following:

    public class Foo
    {
        public Bar Bar { get; set; }
    }
    
    public class Foo2
    {
        public Bar Bar { get; set; }
    }
    
    public class Bar
    {
        public int Id { get; set; }
    
        public Bar()
        {
            Id = 3;
        }
    }
    
    CreateMap<Foo, Foo2>()
        .ForMember(
            dest => dest.Bar,
            opt => opt.MapFrom(src => src.Bar == null ? new Bar() : src.Bar));
    

    ...so I'm wondering if the problem is not actually with your mapping?

    0 讨论(0)
提交回复
热议问题