AutoMapper Map If Not Null, Otherwise Custom Convert

前端 未结 4 1199
伪装坚强ぢ
伪装坚强ぢ 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 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()
        .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?

提交回复
热议问题