[英]Configuring AutoMapper without Generics
I am trying to configure AutoMapper without using generics as I want to configure it at runtime. 我想在不使用泛型的情况下配置AutoMapper,因为我想在运行时进行配置。
I want to configure the SubstiteNulls method and be able to do the equivalent of: 我想配置SubstiteNulls方法,并能够执行以下操作:
Mapper.CreateMap<Source, Dest>()
.ForMember(dest => dest.Value, opt => opt.NullSubstitute("Other Value"));
But I can't figure out how to do this. 但是我不知道该怎么做。 You can pass they Type objects into the
CreateMap
factory method but when you use the ForMember
method, the opt
object does not contain the NullSubstitute
method and I imagine this is due to the lack of generic that I am using here. 您可以将它们的Type对象传递给
CreateMap
工厂方法,但是当您使用ForMember
方法时, opt
对象不包含NullSubstitute
方法,我想这是由于我在这里使用的泛型缺乏。
Any ideas on how I can achieve this? 关于如何实现此目标的任何想法?
These are the options that I am getting: 这些是我得到的选择:
Currently the NullSubstitute
configuration is not available on the IMappingExpression
interface which is used when you are using the non generic version of CreateMap
. 当前,在使用非通用版本的
CreateMap
时,将在IMappingExpression
接口上使用NullSubstitute
配置。
There is no limitation which is preventing Automapper to have this method on the IMappingExpression
so currently this is just not supported. 没有限制,可以阻止
IMappingExpression
在IMappingExpression
上使用此方法,因此当前不支持此方法。
You have three options: 您有三种选择:
Or if you want a quick but very dirty solution. 或者,如果您想要快速但非常肮脏的解决方案。 With reflection you can get the underlaying
PropertyMap
from the configuration and call the SetNullSubstitute
method on it: 通过反射,您可以从配置中获取底层的
PropertyMap
并对其调用SetNullSubstitute
方法:
Mapper.CreateMap(typeof(Source), typeof(Dest)) .ForMember("Value", opt => { FieldInfo fieldInfo = opt.GetType().GetField("_propertyMap", BindingFlags.Instance | BindingFlags.NonPublic); var propertyMap = (PropertyMap) fieldInfo.GetValue(opt); propertyMap.SetNullSubstitute("Null Value"); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.