[英]AutoMapper returnning empty and null
根據下面將 Dto 映射到 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; }
}
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; }
}
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 !
除了NullSubstitute
for Internal 之外,您的設置對我來說很好。 如果源值是 null 沿成員鏈的任何位置,它將替換,但源上沒有Internal
。 例如,您可以執行以下操作:
.AfterMap((dto, model) => model.Internal ??= "NotNull");
附言
對於Id
NullSubstitute
作品( .ForMember(dest => dest.Id, opt => opt.NullSubstitute(Guid.Empty))
)
我意識到問題出在模型綁定而不是映射
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.