我什么时候应该使用 AutoMapper,什么时候不 [英] When should I be using AutoMapper and when not

查看:60
本文介绍了我什么时候应该使用 AutoMapper,什么时候不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据层,其中包含我的 EF6 DbFirst edmx、存储库和 AutoMappings.

I have a Data layer which holds my EF6 DbFirst edmx, repositories, and AutoMappings.

对于我的数据层中的每个自动生成的实体,我还有一个带有 Poco 的模型层.除了一些名称更改外,属性几乎完全匹配.

I also have a Model layer with a Poco for each auto generated entity in my Data layer. The properties pretty much match exactly except for a few name changes.

AutoMapper 仅安装到我的 DataLayer 中,这是我在配置文件中设置所有映射的地方.在这一点上,我有一个从每个 DataLayer 实体到每个 ModelLayer 实体以及每个 ModelLayer 实体到每个 DataLayer 实体的映射.任何名称更改都在映射中指定.

AutoMapper is installed to my DataLayer only and this is where I set all of my mappings in a config file. At this point I have a mapping from each DataLayer entity to each ModelLayer entity and each ModelLayer entity to each DataLayer entity. Any name changes are specified in the mappings.

因为它在我的存储库保存方法中以这种方式设置,该函数从 ModelLayer 接收一个对象,然后映射到一个 DataLayer 对象,以便我可以将它发送到 DbContext.在我的存储库中提取信息时,我使用 DbContext 进行检索,然后使用 AutoMapper 函数映射到模型,以便该函数可以作为 Model.entity 返回.

Since it is setup this way in my repository save methods the function takes in an object from the ModelLayer but then is mapped to a DataLayer object so I can send it to the DbContext. When pulling information in my repository I use the DbContext to retrieve and then the AutoMapper function to map to Model so the function can return as Model.entity.

我的业务层和 Web 应用程序仅使用模型实体.如果这方面有任何问题,请告诉我.

My business layer and web app only use the model entities. If anything seems wrong about this please let me know.

另一件事是在控制器中的 GET 和 POST 操作期间从 ModelLayer 映射到 ViewModel,反之亦然.在这里双向映射也正常吗?此时我是否需要将 AutoMapper 安装到我的网络应用程序中?

The other thing is mapping from ModelLayer to ViewModel and vice versa during GET and POST Actions in my controller. Is it normal to map both ways here too? Do I need to install AutoMapper to my web app at this point?

推荐答案

当我想摆脱无聊的左侧右侧代码时,我会使用 AutoMapper.如果复制数据的逻辑不是很明显,我会恢复到手动映射.

I use AutoMapper when I want to get rid of boring left-hand-side right-hand-side code. If the logic isn't completely obvious for copying data, I revert back to manual mapping.

现在这意味着我在所有 GET 和 POST 上都使用 AutoMapper 的 LINQ 投影.

These days this means I use LINQ projections from AutoMapper on all GETs, and sparingly on POSTs.

这篇关于我什么时候应该使用 AutoMapper,什么时候不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆