Brian David Berman
Brian David Berman

Reputation: 7694

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.

Upvotes: 1

Views: 1718

Answers (3)

CXRom
CXRom

Reputation: 103

Other option is CX.Mapper very simple to use and you dont need to precofig the Map:

[HttpGet]
public ActionResult Edit(int id)
{
  var item = this.db.Items.Find(id);
  var model = CX.Mapper.Mapping.MapNew<Item, ItemDto>(item);
  return View(model);
}

[HttpPost]
public ActionResult Edit(ItemDto model)
{
  if(Model.IsValid)
  {
    var item = this.db.Items.Find(ItemDto.Id);
    CX.Mapper.Mapping.Map<ItemDto, Item>(model, item);
    this.db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(model);
}

You can install with NuGet

Upvotes: 0

Jesse
Jesse

Reputation: 8393

I would invite you to review a framework such automapper which gives you the ability to easily perform object to object mapping.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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.

Upvotes: 4

Related Questions