从 AutoMapper 定义的映射中获取所有定义的映射
假设我有两个类:CD 和 CDModel,映射定义如下:
Mapper.CreateMap<CDModel, CD>()
.ForMember(c => c.Name, opt => opt.MapFrom(m => m.Title));
是否有一种简单的方法来检索原始 表达式,如 c =>; c.Name(源)和m =>映射中的 m.Title(目的地)?
我尝试过这个,但我错过了一些东西......
var map = Mapper.FindTypeMapFor<CDModel, CD>();
foreach (var propertMap in map.GetPropertyMaps())
{
var source = ???;
var dest = propertMap.DestinationProperty.MemberInfo;
}
如何获取源和目标表达式?
Let's assume that I've two classes : CD and CDModel, and the mapping is defined as follows:
Mapper.CreateMap<CDModel, CD>()
.ForMember(c => c.Name, opt => opt.MapFrom(m => m.Title));
Is there an easy way to retrieve the original expression like c => c.Name (for source) and m => m.Title (for destination) from the mapping?
I tried this, but I miss some things...
var map = Mapper.FindTypeMapFor<CDModel, CD>();
foreach (var propertMap in map.GetPropertyMaps())
{
var source = ???;
var dest = propertMap.DestinationProperty.MemberInfo;
}
How to get the source and destination expressions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
沿着与你正在做的事情相同的道路......
你到底想要如何表达?你想要底层的 Lambas 吗?
如果是的话看看
Going along the same path as what you were doing ...
How exactly do you want the expressions? Are you wanting the underlying Lambas?
If so look at
我还发现 var map = Mapper.GetAllTypeMaps(); 也很有用,因为您可以搜索 SourceType 或 DestinationType。
I also find
var map = Mapper.GetAllTypeMaps();
to be useful too, as you can search for the SourceType or DestinationType.我正在使用 Automapper 7.0,现在语法不同了。例如,
然后您可以使用以下方式调用它:
或者如果您想转储所有内容,则可以这样做。
I'm using Automapper 7.0 and the syntax is different now. For example,
And then you can call it using:
or if you want to dump out everything, then do like this.
在 AutoMapper 12 上,如果不使用反射,您似乎不再能够从
IMapper
或IConfigurationProvider
获取有关地图或配置文件的信息。如果您希望避免反射,那么您可以通过将配置文件强制转换为
IProfileConfiguration
来直接从配置文件中获取至少一些信息。如果您像我一样使用 DI 注册您的配置文件,并且您只需要映射到/来自的类型,那么您可以按照此方法执行某些操作来获取所有源/目标类型:
我不确定是否
IProfileConfiguration.TypeMapConfigs
属性(或该接口上的任何其他属性)将提供有关所涉及的成员或表达式等的信息,但值得检查。希望这对某人有帮助。
On AutoMapper 12 you no longer appear to be able to get information on the maps or profiles from
IMapper
or fromIConfigurationProvider
without using reflection.If you'd rather avoid reflection, then you can get at least some of the information from the profiles directly by casting them to
IProfileConfiguration
.If you register your profiles with DI like I do, and you just need the types you're mapping to/from, then you can do something along the lines of this to get all source/destination types:
I'm not sure if the
IProfileConfiguration.TypeMapConfigs
property (or any of the other properties on that interface) will provide information on the members involved or the expressions, etc., but it's worth checking.Hopefully this helps someone.