简体   繁体   English

AutoMapper 返回空和 null

[英]AutoMapper returnning empty and null

Mapping a Dto to a Model per below - on mapping = a completely empty model!根据下面将 Dto 映射到 Model - 映射 = 一个完全空的模型!

There are a mix of nullable and non-nullable references in both objects.两个对象中都混合有可空引用和不可空引用。

The Model Model


    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; }
    }

The Dto 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; }
    }

The Map and execution - Dto to Model Map 和执行 - Dto 到 Model


    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 !

Your set up works fine for me except NullSubstitute for Internal.除了NullSubstitute for Internal 之外,您的设置对我来说很好。 It will substitute if the source value is null anywhere along the member chain, but you have no Internal on the source.如果源值是 null 沿成员链的任何位置,它将替换,但源上没有Internal You can do something like this for example:例如,您可以执行以下操作:

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

PS附言

for Id NullSubstitute works ( .ForMember(dest => dest.Id, opt => opt.NullSubstitute(Guid.Empty)) )对于Id NullSubstitute作品( .ForMember(dest => dest.Id, opt => opt.NullSubstitute(Guid.Empty))

I realized the problem was in model-binding not mapping我意识到问题出在模型绑定而不是映射

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM