我需要双向创建 automapper createmap 吗?
这可能是一个愚蠢的问题! (n00b 到 AutoMapper 并且时间很短!)
我想使用 AutoMapper 从 EF4 实体映射到 ViewModel 类。
1)如果我打电话
CreateMap<ModelClass, ViewModelClass>()
,那么我还需要打电话
CreateMap<ViewModelClass, ModelClass>()
来执行相反的操作吗?
2)如果两个类具有相同的属性名称,那么我是否需要 CreateMap 语句,或者这只是用于“特定/自定义”映射?
This might be a stupid question! (n00b to AutoMapper and time-short!)
I want to use AutoMapper to map from EF4 entities to ViewModel classes.
1) If I call
CreateMap<ModelClass, ViewModelClass>()
then do I also need to call
CreateMap<ViewModelClass, ModelClass>()
to perform the reverse?
2) If two classes have the same property names, then do I need a CreateMap statement at all, or is this just for "specific/custom" mappings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为偶然发现这个问题的人提供信息。现在似乎有一种内置方法可以通过在
CreateMap()
配置链末尾添加.ReverseMap()
调用来实现反向映射。For the info of the people who stumble upon this question. There appears to be now a built-in way to achieve a reverse mapping by adding a
.ReverseMap()
call at the end of yourCreateMap()
configuration chain.在 AutoMapper 中,您有一个源类型和一个目标类型。因此,仅当您有相应的 CreateMap 时,您才能够在该 Source 类型和 Destination 类型之间进行映射。因此,回答您的问题:
Map
时会抛出异常,告诉您源和目标之间不存在映射类型。In AutoMapper you have a Source type and a Destination type. So you will be able to map between this Source type and Destination type only if you have a corresponding CreateMap. So to answer your questions:
Map<TSource, TDest>
telling you that a mapping doesn't exist between the source and destination type.我使用了扩展方法来映射两种
用法:
I've used an extension method do mapping both ways
usage:
CreateMap().ReverseMap()
。Member
(Property,Field,GetMethod()),则无需调用CreateMap
。实际上,如果TDest
中的每个member
都存在于TSrc
中,则不需要调用CreateMap
CreateMapCreateMap<ModelClass, ViewModelClass>().ReverseMap()
.Member
(Property,Field,GetMethod()), you needn't callCreateMap<TSrc,TDest>
. Actually, if everymember
inTDest
are all exist inTSrc
, you needn't callCreateMap<TSrc,TDest>
. The following code works.