Reputation: 2435
I am trying to figure out something that I am not sure if it is possible. My goal is that I have an extension method called convertToPersonModel that copies my PersonViewModel to the PersonModel. Is it possible that I can change the parameters to accept any ViewModel and convert it to it's normal model. For instance, I could pass in the EmployeeViewModel to be converted to EmployeeModel, or RoleViewModel to the RoleModel all in one method.
This is my extension method:
public static PersonModel ConvertToPersonModel(this PersonViewModel viewModel)
{
var model = new Product(){
FirstName = viewModel.FirstName;
LastName = viewModel.LastName;
}
return model;
}
So the goal would be to be able to pass in any view model and figure out the properties of the relevant model (which properties the normal model has) and assign those values depending on which viewmodel/model pair it is. This may be confusing, let me know if you need more clarification.
Somethings like:
public static Model ConvertToModel(this ViewModel viewModel)
{
var model = new findWhichModelisRelatesToViewModel(){
1stproperty = viewModel.relevantProperty;
2ndproperty = viewModel.relevantProperty;
}
return model;
}
With Model being the model that correlates to the sent in view model.
Upvotes: 0
Views: 4457
Reputation: 3810
You cannot possibly create a non-generic extension method that will handle conversion from all your domain models to viewmodels and vice versa. Rather what you want as stated in comments above is to tell which viewmodel corresponds to which model and map anytime you want and the perfect lib for this is AutoMapper.
First you declare a map:
Mapper.CreateMap<Order, OrderDto>();
Then you get it mapped:
OrderDto dto = Mapper.Map<OrderDto>(order);
You also get much control on this
Upvotes: 2