[英]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.