AutoMapper 返回空和 null
AutoMapper returnning empty and null
根据以下内容将 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 !
您的 works fine for me except NullSubstitute
内部设置。如果源值在成员链中的任何位置为 null,但您在源上没有 Internal
,它将被替换。例如,您可以这样做:
.AfterMap((dto, model) => model.Internal ??= "NotNull");
P.S.
对于 Id
NullSubstitute
有效 (.ForMember(dest => dest.Id, opt => opt.NullSubstitute(Guid.Empty))
)
我意识到问题出在模型绑定而不是映射
根据以下内容将 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 !
您的 works fine for me except NullSubstitute
内部设置。如果源值在成员链中的任何位置为 null,但您在源上没有 Internal
,它将被替换。例如,您可以这样做:
.AfterMap((dto, model) => model.Internal ??= "NotNull");
P.S.
对于 Id
NullSubstitute
有效 (.ForMember(dest => dest.Id, opt => opt.NullSubstitute(Guid.Empty))
)
我意识到问题出在模型绑定而不是映射