Reputation: 2924
I have several objects as shown in the UML diagram below:
I have written a single page MVC application which handles all objects derived from the same interfce and differ in a few properties only. My model is the coverage of all possible properties.
The thing is that when I post data to DAL I must use entites, not Models. My Controller and View uses Model, but DAL methods expect either Entity A or Entity B.
Now I want to design a class to make appropriate coversions. I can make a class having methods ConvertToA() and ConvertToB() and call methods of this class. This is the most basic layout which comes to mind at first.
But is there an appropriate Design Pattern for this, or what could be the most flexible and efficient way to accomplish this task?
Regards.
Upvotes: 1
Views: 1695
Reputation: 5137
You could use AutoMapper for object to object conversion. In your above mentioned case, a POST action would look like below:
[HttpPost]
public ActionResult TestAction(Model model)
{
var entityA = _mappingService.Map<Model, EntityA>(model);
testService.TestMethod(entityA);
return View();
}
You need to define mapping something like this for each Model -> ViewModel mapping (and viceversa):
Mapper.CreateMap<EntityA, Model>();
Mapper.CreateMap<Model, EntityA>();
if the objects are compatible, the conversion is supported. You could also configure mapping of individual object properties like:
Mapper.CreateMap<Order, OrderViewModel>()
.ForMember(o => o.OrderDescription, b => b.MapFrom(z => z.Description))
.ForMember(o => o.OrderId, b => b.MapFrom(z => z.Id));
Upvotes: 2