如何将DTO从EF映射到模型

本文关键字:映射 模型 EF DTO | 更新日期: 2023-09-27 18:19:07

我有以下模型Person在我的UI MVC层:

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; }
}

在我的数据层,我有一个类具有相同的属性名称,但不同的元(自然):

public partial class Person : EntityObject { ... }

我怎么能从我的数据层返回数据到我的MVC UI层没有数据层知道MVC UI层?

注意:我也有一个简单的IPerson接口,具有相同的属性名称。

如何将DTO从EF映射到模型

您可以使用AutoMapper在域模型和视图模型之间进行映射。是MVC层知道数据层,而数据层不需要知道MVC层。

这里有一个常见的模式:

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

,反之:

[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");
}

正如你所看到的,数据层不需要知道MVC层的任何信息。需要了解数据层的是MVC层

我想请您回顾一下这样一个automapper框架,它使您能够轻松地执行对象到对象的映射。

另一个选项是CX。Mapper使用起来非常简单,你不需要预先配置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);
}

你可以安装NuGet