【发布时间】:2020-11-13 12:52:33
【问题描述】:
我需要使用 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 的情况下映射这种类型结构?
【问题讨论】:
-
@LucianBargaoanu 似乎 IncludeMembers 是我需要的,但我没有此方法可用。我的 AutoMapper 版本是 7.0.1,我建议以后添加这个方法
-
升级或重命名以使用默认命名约定。
标签: c# automapper