[英]AutoMapper flattening
我需要使用 AutoMapper 将源映射到目标。 类型结构如下所示:
Source {
public string SourceField1;
public string SourceField2;
public InnerSource Inner;
}
InnerSource {
public string InnerSourceField3;
public string InnerSourceField4;
}
Destination {
public string DestinationField1;
public string DestinationField2;
public string DestinationField3;
public string DestinationField4;
}
我的解决方案看起来像:
CreateMap<Source, Destination>()
.ForMember(dest => dest.DestinationField1, opt => opt.MapFrom(src => src.SourceField1))
.ForMember(dest => dest.DestinationField2, opt => opt.MapFrom(src => src.SourceField2))
.AfterMap((src, dest, context) => context.Mapper.Map(src.Inner, dest));
CreateMap<InnerSource, Destination>()
.ForMember(dest => dest.DestinationField3, opt => opt.MapFrom(src => src.InnerSourceField3))
.ForMember(dest => dest.DestinationField4, opt => opt.MapFrom(src => src.InnerSourceField4))
所有这些东西似乎都有效,但不适用于 EF 和 ProjectTo 扩展方法,因为 AfterMap 与 EF 不“兼容”。
所以我的问题是如何与 EF 一起工作? 我应该使用一些解决方法还是有另一种方法来映射没有 AfterMap 的这种类型结构?
CreateMap<Source, Destination>().IncludeMembers(s => s.Inner)
.ForMember(dest => dest.DestinationField1, opt => opt.MapFrom(src => src.SourceField1))
.ForMember(dest => dest.DestinationField2, opt => opt.MapFrom(src => src.SourceField2));
CreateMap<InnerSource, Destination>()
.ForMember(dest => dest.DestinationField3, opt => opt.MapFrom(src => src.InnerSourceField3))
.ForMember(dest => dest.DestinationField4, opt => opt.MapFrom(src => src.InnerSourceField4));
你也应该知道你可以拒绝前缀
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.