[英]How to map DTO from EF to Model
我的UI MVC层中具有以下模型Person:
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; }
}
在我的数据层中,我有一个具有相同属性名称的类,但具有不同的meta(自然地):
public partial class Person : EntityObject { ... }
如何在不让数据层了解MVC UI层的情况下将数据从数据层返回到MVC UI层?
注意:我也有一个具有相同属性名称的简单IPerson界面。
您可以使用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层需要了解数据层。
我邀请您回顾一下自动映射器这样的框架,它使您能够轻松执行对象到对象的映射。
另一个选项是CX.Mapper ,使用起来非常简单,您无需预先配置地图:
[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进行安装
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.