When should I be using AutoMapper and when not

2019-04-29 12:34发布

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

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 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.

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.

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

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?

1条回答
叛逆
2楼-- · 2019-04-29 13:25

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.

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

查看更多
登录 后发表回答