my mvc3 project has following layers.
controller -> service -> repository.
I need to map ViewModel to Entity, not sure which layer is the right one to put the code in.
I know its either controller or service, please let me know which one I should use, and if you could please let me know why.
thank you.
Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.
AutoMapper is a conventions-based mapping system that allows you to copy values from an instance of one class to an instance of another class using pre-defined maps.
AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.
I need to map ViewModel to Entity, not sure which layer is the right one to put the code in.
Controller of course. The service and repository layers don't know what a view model means. They manipulate only domain models.
So inside the controller you use the .Map<TSource, TDest>
call to do the mapping back and forth between a domain model and a view models. But the mapping definition itself (.CreateMap<TSource, TDest>
call) is done once per AppDomain lifetime, ideally in a Profile
.
So let's consider a couple of typical workflows within a controller action in RESTful terms
GET
(SELECT in RDBMS terms):
PUT
(INSERT in RDBMS terms):
DELETE
(DELETE in RDBMS terms)
POST
(UPDATE in RDBMS terms):
.Map<TSource, TDest>
method: Mapper.Map<ADomain, ViewModel>(domainInstanceControllerRetrievedUsingTheId, viewModelInstancePassedAsArgument);
Armed with those 4 workflows you are ready for the CRUD world.
P.S. A REST reminder:
Create = PUT
Retrieve = GET
Update = POST
Delete = DELETE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With