本文介绍了将对象传递给 AutoMapper 映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 AutoMapper,被映射到的实体的一些值是我当前方法中的变量.我试过谷歌它,但无济于事.我可以将一组 KeyValue Pairs 或一个对象或其他东西传递给我的映射以使其使用这些值吗?
I am working with AutoMapper and some of the values for the entity being mapped to are variables in my current method. I have tried to Google it but to no avail. Can I pass a set of KeyValue Pairs or an object or something to my mapping to have it use those values?
//comment variable is a Comment class instance
var imageComment = AutoMapper.Mapper.Map<Data.ImageComment>(comment);
//I want to pass in imageId so I dont have to manually add it after the mapping
imageComment.ImageId = imageId;
推荐答案
AutoMapper 开箱即用地处理这种键值对方案.
AutoMapper handles this key-value pair scenario out of the box.
Mapper.CreateMap<Source, Dest>()
.ForMember(d => d.Foo, opt => opt.ResolveUsing(res => res.Context.Options.Items["Foo"]));
然后在运行时:
Mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");
深入研究上下文项目有点冗长,但你去了.
A bit verbose to dig into the context items but there you go.
这篇关于将对象传递给 AutoMapper 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!