Currently I use private static methods in my controller file to map domain model to view model and vice-versa. Like below:
public ActionResult Details(int personID)
{
Person personDM = service.Get(personID);
PersonViewModel personVM = MapDmToVm(personDM);
return View(personVM);
}
private static PersonViewModel MapDmToVm(Person dm)
{
PersonViewModel vm;
// Map to VM
return vm;
}
Is there any other standard way to do this?
I prefer to put the mapping logic inside the view model (dto) class, because we want to keep the domain model as clean as possible and also the domain model might change overtime.
public class Person
{
public string Name {get; set;}
}
public class PersonViewModel
{
public string Text {get; set;}
public static implicit operator PersonViewModel(Person dm)
{
var vm = new PersonViewModel { Text = dm.Name };
return vm;
}
public static implicit operator Person(PersonViewModel vm)
{
var dm = new Person { Name = vm.Text };
return dm;
}
}
and use it in the controller without explicit casting.
Person dm = service.Get(id);
PersonViewModel vm = dm;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With