[英]How to map object with custom class property that returns object with null property values instead of returning null using Automapper
我有这些课
public class SemModel
{
public int SemId {get; set}
public string AreaId {get; set}
public string Longitude {get; set}
public string Latitude {get; set}
}
public class SemDto
{
public int SemId {get; set}
public AreaDto Area {get; set}
}
public class AreaDto
{
public string AreaId {get; set}
public string Longitude {get; set}
public string Latitude {get; set}
}
我希望能够将 SemModel 映射到 SemDto,其中如果 AreaId、经度和纬度为空,则 SemDto.Area 使用具有空值的 AreaId、经度和纬度属性进行初始化。
实际输出是我有一个 SemDto,其中 Area 属性为空
这是我的映射
CreateMap<SemModel, SemDto>()
.ForMember(dest => dest.Area, opt => opt.MapFrom(src => new AreaDto
{
AreaId = src.AreaId,
Longitude = src.Longitude,
Latitude = src.Latitude
}));
鉴于:
new SemModel(){SemId =1, AreaId =null, Longitude=null, Latitude=null}
预期输出:
new SemDto(){SemId = 1, Area = new Area(){ AreaId =null, Longitude =null, Latitude =null}}
实际输出:
new SemDto(){SemId = 1, Area = null}
另一个尝试 1
.ForPath(dest => dest.Area.AreaId, opt => opt.MapFrom(src => src.AreaId))
.ForPath(dest => dest.Area.Longitude, opt => opt.MapFrom(src => src.Longitude))
.ForPath(dest => dest.Area.Latitude, opt => opt.MapFrom(src => src.Latitude));
仍然没有运气。 好!
cfg.CreateMap<SemDto, SemModel>().IncludeMembers(s=>s.Area).ReverseMap();
cfg.CreateMap<AreaDto, SemModel>().ForMember(d=>d.SemId, o=>o.Ignore()).ReverseMap();
它使用unflattening 。 ForPath
也有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.