我开始使用 AutoMapper 时出现了一些疑问。 将 dto 映射到域模型的正确方法在哪里? 我这样做:
DTO:
public class PersonInsert
{
[Required]
public string Name { get; set; }
public string LastName { get; set; }
}
行动:
[HttpPost]
public ActionResult Insert(PersonInsert personInsert)
{
if (ModelState.IsValid)
{
new PersonService().Insert(personInsert);
return RedirectToAction("Insert");
}
return View("Insert");
}
服务:
public class PersonService
{
public int Insert(PersonInsert personInsert)
{
var person = Mapper.Map<PersonInsert, Person>(personInsert);
return new PersonRepository().Insert(person);
}
}
存储库:
public class PersonRepository
{
internal int Insert(Person person)
{
_db.Person.Add(person);
_db.SaveChanges();
return person.Id;
}
}
那么,这是正确的吗?我的服务应该知道域吗?还是我应该只在存储库中进行绑定(bind)?在 DTO 中使用 [Required] 是否正确?
最佳答案
我几乎永远不会从 DTO 创建实体 - 我将在下面解释原因。我会使用请求对象来允许工厂方法构建实体:
要求:
public class InsertPersonRequest
{
[Required]
public string Name { get; set; }
public string LastName { get; set; }
}
行动:
[HttpPost]
public ActionResult Insert(InsertPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
InsertPersonRequest request = InsertPersonViewModelMapper.CreateRequestFrom(viewModel);
new PersonService().Insert(request );
return RedirectToAction("Insert");
}
return View("Insert");
}
服务:
public class PersonService
{
public int Insert(InsertPersonRequest request)
{
var person = Person.Create(request.name, request.LastName);
return new PersonRepository().Insert(person);
}
}
存储库保持不变。
这样,创建 Person 的所有逻辑都位于 person 的 Factory 方法中,因此业务逻辑被封装在域中——派生字段、默认字段等。
您正在做的事情的问题是必须在 UI 中创建 DTO,然后将所有字段映射到实体 - 这是业务逻辑渗入服务层的必经之路, UI,或任何不应出现的地方。
请再读一遍 - 这是一个非常严重的错误,我一次又一次地看到它。
但是,我会在服务层使用 AutoMapper 来返回 DTO:
服务:
public class PersonService
{
public PersonDto GetById(intid)
{
var person = new PersonRepository().GetById(id);
var personDto = Mapper.Map<Person, PersonDto>(person);
return personDto
}
}
关于asp.net-mvc - 将 DTO 绑定(bind)到域模型的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12584966/