Reputation: 73
I have more than 8 pages in a modules for a .NET MVC3 based project. I have a single controller to handle all the pages. When I get the value from the view, I have to convert to the local model for doing the logic in the business layer. To convert the model from ViewModel
, I'm using Auto Mapper. Is there any possibility for making the Auto Mapper as a generic function?
Here is the code which I'm using:
Mapper.CreateMap<WorkLoadRatioViewModel, WorkLoadRatio>();
WorkLoadRatio _workloaddata = Mapper.Map<WorkLoadRatioViewModel, WorkLoadRatio>(_vmodel);
Mapper.CreateMap<LeadTimeDayDetailsViewModel, LeadTimeDayDetails>();
LeadTimeDayDetails _leadtimedata = Mapper.Map<LeadTimeDayDetailsViewModel,LeadTimeDayDetails>(_vmodel);
Is there a way to bring all the code just to call a generic function? For example,
public static TModel ToModel<TModel>(TModel model,TViewModel viewmodel)
where TModel : class
{
//mapper function to return the TModel OBject.
}
Upvotes: 0
Views: 1380
Reputation: 24526
Is this what you're trying to do:
public TDest Map<TSource, TDest>(TSource viewModel)
{
Mapper.CreateMap<TSource, TDest>();
TDest result = Mapper.Map<TSource, TDest>(viewModel);
return result;
}
public ActionResult MyAction(WorkLoadRationViewModel viewModel)
{
WorkLoadRatio model = Map<WorkLoadRationViewModel, WorkLoadRatio>(viewModel);
}
Upvotes: 6