[英]How to map DTO from EF to Model
I have the following model Person in my UI MVC layer: 我的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; }
}
In my data layer, I have a class with the same property names, but different meta (naturally): 在我的数据层中,我有一个具有相同属性名称的类,但具有不同的meta(自然地):
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? 如何在不让数据层了解MVC UI层的情况下将数据从数据层返回到MVC UI层?
Note: I also have a simple IPerson interface with the same property names as well. 注意:我也有一个具有相同属性名称的简单IPerson界面。
You could use AutoMapper to map between the domain model and the view model. 您可以使用AutoMapper在域模型和视图模型之间进行映射。 It is the MVC layer that knows about the data layer, but the data layer doesn't need to know about the MVC layer.
MVC层了解数据层,但是数据层不需要了解MVC层。
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. 如您所见,数据层不需要了解MVC层。 It's the MVC layer that needs to know about the data layer.
MVC层需要了解数据层。
我邀请您回顾一下自动映射器这样的框架,它使您能够轻松执行对象到对象的映射。
Other option is CX.Mapper very simple to use and you dont need to precofig the Map: 另一个选项是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);
}
You can install with NuGet 您可以使用NuGet进行安装
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.