What is the point of AutoMapper? Could someone give me a really simple example?
I have watched the video on it, but it is just not clicking.
Sam
What is the point of AutoMapper? Could someone give me a really simple example?
I have watched the video on it, but it is just not clicking.
Sam
Typically AutoMapper is great at mapping between data entities and business models. E.g., lets say for instance, I have a data domain type, call it
PersonEntity
, and it has an array of properties:FirstName
,Surname
,Gender
etc. I don't want to expose my data domain type through to the consuming application, so I can define business domain types, e.g.Person
, now thePerson
type can contain additional business logic, such asGetRelatedPersons
, etc, which may not be functionality tied to your data domain. In this case, I have two types,PersonEntity
andPerson
which at some point I will have to write boilerplate code to copy the properties from one to the other. I could do this a variety of ways, I could:1.Copy Constructor:
2.Generalised Mapping Method:
3.Implicit/Explicit Conversion:
But what AutoMapper allows you to do, is easily create a mapping process between those two types. So in its simiplist form, I could:
By using a convention-first approach, the AutoMapper framework will translate matching properties from one instance to the next. It also allows you to customise how the types are mapped if you want more fine grained control.
Hope that helps.
say you have two classes
I would say, (A is Source, B is destination.)
so now I can have an object A with some filled in properties, and say
now the properties got mapped to the object for you :D
its a fancy copy constructor if you are familar with C++ :D, Hope that helps
In ASP.NET MVC (since you've tagged that), AutoMapper makes the painful task of mapping your ViewModels to your domain models (e.g Entity Framework POCO's, Linq-To-Sql classes) much easier.
Most of the time, our ViewModels contain many entities, so we can't simply do
context.AddObject(viewModel)
. Usually we have to break apart the ViewModel, do multiple adds, etc.This manual stitching makes your Controller "fat", which is the opposite of what it should be.
Enter AutoMapper.
There is a good/simple example here of the above here.