如何根据目标属性名称在 Automapper 中执行字符串查找?
我想将这样的代码中的属性查找概括
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetValue("FirstName"))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.GetValue("LastName"))
... (repeated for many properties)
为单行代码,从概念上讲是这样的:
// How can I access the property name?
.ForAllMembers(opt => opt.MapFrom(src => src.GetValue([[PROPERTYNAME]]))
“源”值几乎总是对 GetValue() 方法进行基于字符串的查找,使用来自的属性名称目的地。我只是不知道如何在“目标”lambda 中定义属性时从“源”lambda 访问该属性的字符串名称。似乎应该有一种方法可以做到这一点,但我没有运气找到相关的例子。
我希望这是有道理的。预先感谢您的任何见解,
杰夫
I'd like to generalize a property lookup from code like this
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetValue("FirstName"))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.GetValue("LastName"))
... (repeated for many properties)
to a one-liner, conceptually something like this:
// How can I access the property name?
.ForAllMembers(opt => opt.MapFrom(src => src.GetValue([[PROPERTYNAME]]))
The "source" value is almost always be a string-based lookup into a GetValue() method, using the property name from the destination. I just don't know how to access the string name of the property from the "source" lambda when it's defined in the "destination" lambda. It seems like there ought to be a way to do this but I'm not having luck finding a relevant example.
I hope this makes sense. Thanks in advance for any insights,
Jeff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用自定义解析器,它使用反射来获取所有属性名称,然后调用源对象的 GetValue() 方法。
You should be able to use a Custom Resolver that uses reflection to get all the property names and then calls your GetValue() method of the source object.
我知道这个问题已经有 2-3 年了,但我遇到了这样的问题,很难找到答案,主要是因为文档中没有记录 IValueResolver 接口。
我最终做了这样的事情:
希望这对某人有帮助。
I know this question is like 2-3 years old, but I ran into something like this and it was very hard to find the answer, mostly because IValueResolver interface is not documented in the documentation.
I ended up doing something like this:
Hope this helps someone.