简体   繁体   中英

AutoMapper returnning empty and null

Mapping a Dto to a Model per below - on mapping = a completely empty model!

There are a mix of nullable and non-nullable references in both objects.

The 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


    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


    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. It will substitute if the source value is null anywhere along the member chain, but you have no Internal on the source. 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)) )

I realized the problem was in model-binding not mapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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