Search code examples
c#asp.net-mvcinterfacemodelseparation-of-concerns

How to map DTO from EF to Model


I have the following model Person in my UI MVC layer:

public class Person
{
     [Required]
     public string FirstName { get; set; }

     [Required]
     public string LastName { get; set; }

     public int PersonTypeID { get; set; }

     [Required]
     public string Phone { get; set; }

     [Required]
     public string Email { get; set; }

}

In my data layer, I have a class with the same property names, but different meta (naturally):

public partial class Person : EntityObject { ... }

How can I return data from my data layer into my MVC UI layer without having the data layer know about the MVC UI layer?

Note: I also have a simple IPerson interface with the same property names as well.


Solution

  • You could use AutoMapper to map between the domain model and the view model. It is the MVC layer that knows about the data layer, but the data layer doesn't need to know about the MVC layer.

    Here's a common pattern:

    public ActionResult Foo()
    {
        var person = _repository.GetPerson();
        var personViewModel = Mapper.Map<Person, PersonViewModel>(person);
        return View(personViewModel);
    }
    

    and the other way around:

    [HttpPost]
    public ActionResult Foo(PersonViewModel personViewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var person = Mapper.Map<PersonViewModel, Person>(personViewModel);
        _repository.UpdatePerson(person);
        return RedirectToAction("Success");
    }
    

    As you can see the data layer doesn't need to know anything about the MVC layer. It's the MVC layer that needs to know about the data layer.