c# - How to convert a model to it's viewmodel based on model name -
i trying figure out not sure if possible. goal have extension method called converttopersonmodel copies personviewmodel personmodel. possible can change parameters accept viewmodel , convert it's normal model. instance, pass in employeeviewmodel converted employeemodel, or roleviewmodel rolemodel in 1 method.
this extension method:
public static personmodel converttopersonmodel(this personviewmodel viewmodel) { var model = new product(){ firstname = viewmodel.firstname; lastname = viewmodel.lastname; } return model; }
so goal able pass in view model , figure out properties of relevant model (which properties normal model has) , assign values depending on viewmodel/model pair is. may confusing, let me know if 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 model correlates sent in view model.
you cannot possibly create non-generic extension method handle conversion domain models viewmodels , vice versa. rather want stated in comments above tell viewmodel corresponds model , map anytime want , perfect lib automapper.
first declare map:
mapper.createmap<order, orderdto>();
then mapped:
orderdto dto = mapper.map<orderdto>(order);
you control on this