patterncsharpMinor
Using AutoMapper to map to and from
Viewed 0 times
mapautomapperusingandfrom
Problem
Sometimes, I need to map from a Domain entity to a ViewModel - to display information.
Other times, I need to map from a ViewModel to a Domain entity - for persistance of data.
Is this kosher or does this code smell?
Other times, I need to map from a ViewModel to a Domain entity - for persistance of data.
Is this kosher or does this code smell?
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
MapObjects();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
private void MapObjects()
{
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
}Solution
Automapper ReverseMap
This is a more succint way to register your classes.
As opposed to the mirrored registration..
This is a more succint way to register your classes.
Automapper is able to create a two-way mapping expression using ReverseMap.private void MapObjects()
{
Mapper.CreateMap();
Mapper.CreateMap().ReverseMap();
Mapper.CreateMap().ReverseMap();
}As opposed to the mirrored registration..
private void MapObjects()
{
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
Mapper.CreateMap();
}Code Snippets
private void MapObjects()
{
Mapper.CreateMap<UserModel, User>();
Mapper.CreateMap<ProductBrandModel, ProductBrand>().ReverseMap();
Mapper.CreateMap<ProductCategoryModel, ProductCategory>().ReverseMap();
}private void MapObjects()
{
Mapper.CreateMap<UserModel, User>();
Mapper.CreateMap<ProductBrandModel, ProductBrand>();
Mapper.CreateMap<ProductBrand, ProductBrandModel>();
Mapper.CreateMap<ProductCategoryModel, ProductCategory>();
Mapper.CreateMap<ProductCategory, ProductCategoryModel>();
}Context
StackExchange Code Review Q#4369, answer score: 3
Revisions (0)
No revisions yet.