When should I be using AutoMapper and when not
Asked Answered
C

1

8

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?

Cari answered 18/2, 2015 at 1:5 Comment(6)
"When should I be using AutoMapper and when not" <- it makes types meaningless, so the answer is "never".Torrietorrin
@MauricioScheffer: I disagree, it's perfectly acceptable to map from the internal model to a viewmodel (outwards) or from a validationmodel to the internal model (inwards).Verdun
So I take it that there is no wrong or right. If you need to go from one similar object to another similar object and don't want to manually set the properties every time you use AutoMapper.Cari
Check out tonymorris.github.io/blog/posts/… for some of the benefits of using types properly. AutoMapper makes it impossible to reason about your code.Torrietorrin
Also recommend "Propositions as types" wadler.blogspot.co.uk/2014/06/… (no need to understand all the type theory). Types without logic are... well, illogical. Best to avoid that.Torrietorrin
Great question and really well asked but unfortunately not a single good answer.Shelashelagh
E
17

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.

Eucken answered 18/2, 2015 at 14:25 Comment(1)
LINQ Projection is great! One thing I like about AutoMapper is that it will warn you if you forgot to map some properties. I worked on a project where we did manual mapping and I found quite a few bugs where the developer simply forgot to map a property manually and it was only caught some weeks later.Gargan

© 2022 - 2024 — McMap. All rights reserved.