【问题标题】:AutoMapper returnning empty and nullAutoMapper 返回空和 null
【发布时间】:2020-07-19 00:04:11
【问题描述】:

根据以下将 Dto 映射到模型 - 映射 = 一个完全空的模型!

在这两个对象中都有可空引用和不可空引用。

模型


    public class TheModel
    {
        public Guid? Id { get; set; }
        public Guid Type { get; set; }
        public string Title { get; set; } = null!
        public string Description { get; set; } = null!;
        public string? ItIsAnything { get; set; }
    
        public string Internal { get; set; } = null!; 
        public string? AnotherInternal { get; set; }
    }

Dto


    public class TheDto
    {
        public Guid? Id { get; set; }
        public Guid Type { get; set; }
        public string? Title { get; set; } //  is nullable in the dto
        public string Description { get; set; } = null!;
        public string? ItIsAnything { get; set; }
    }

映射和执行 - Dto 到模型


    CreateMap<TheDto, TheModel>()
       .ForMember(dest => dest.Id, opt => opt.MapFrom(dto => dto.Id ?? Guid.Empty))
    
    // attempt for non-nullable references in Model that are nullable in Dto
    
       .ForMember(dest => dest.Internal , opt => opt.NullSubstitute("")); 
    
    // execute
    var dto = new TheDto{
        Id = null,
        Type = Guid.NewGuid(),
        Title = null;
        Description = "any desc";
    }
    
    var model = _mapper.Map<TheModel>(dto);
    
    ///// model is all empty !

【问题讨论】:

    标签: c# automapper c#-8.0 nullable-reference-types


    【解决方案1】:

    您的设置 works fine for me 除了 NullSubstitute 用于内部。如果源值在成员链中的任何位置为空,它将替代,但源上没有Internal。例如,您可以执行以下操作:

    .AfterMap((dto, model) => model.Internal ??= "NotNull");
    

    附言

    对于Id NullSubstitute 有效(.ForMember(dest =&gt; dest.Id, opt =&gt; opt.NullSubstitute(Guid.Empty))

    【讨论】:

    • 谢谢 - 你是对的,我的设置很好 = 我意识到问题出在模型绑定而不是映射 - 我正在撤回问题 - 感谢您抽出宝贵时间
    【解决方案2】:

    我意识到问题出在模型绑定而不是映射

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2019-08-31
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多