Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I place my domain model to view model mapping code?

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?

like image 731
Saravana Avatar asked Jun 10 '14 07:06

Saravana


1 Answers

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;
like image 122
Yuliam Chandra Avatar answered Oct 16 '22 22:10

Yuliam Chandra