在我的 ASP.net mvc 应用程序中,我使用服务层和存储库来保持我的 Controller 精简。典型的细节只读 View 如下所示:
public ActionResult Details(int id)
{
var project = _projectService.GetById(id);
return View(Mapper.Map<Project, ProjectDetails>(project));
}
服务层:
public class ProjectService : IProjectService
{
public Project GetById(int id)
{
var project = _projectRepository.GetProject(id);
// do some stuff
return project;
}
}
public class ProjectRepository : IProjectRepository
{
public Project GetProject(int id)
{
return context.Projects.Find(id);
}
}
从服务层移动到 View 模型非常容易,因为有自动映射器,它可以很容易地把东西扁平化。将另一个直接从 View 模型传递到我的服务层是我努力想出一个好的解决方案的地方。
在像创建操作这样的情况下,什么是好的方法?
[HttpPost]
public ActionResult Create(CreateProjectViewModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// TODO
return RedirectToAction("Index");
}
我很确定服务层应该对 View 模型一无所知,但我也不认为 AutoMapper 在这种情况下也能很好地工作,因为它不擅长采用平面模型并将其变成复杂的对象。
我的 Controller 应该如何与服务层通信?我想让 Controller 中的代码尽可能简洁。
最佳答案
您可以定义一个双向映射,然后反过来:
[HttpPost]
public ActionResult Create(CreateProjectViewModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
Project project = Mapper.Map<CreateProjectViewModel, Project>(model);
// pass the project entity to your service layer
_projectService.Create(project);
return RedirectToAction("Index");
}
或者如果您正在更新一个实体,您可能首先想要从服务中获取您想要更新的现有实体:
[HttpPost]
public ActionResult Update(CreateProjectViewModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
Project project = _projectService.GetById(model.Id);
Mapper.Map<CreateProjectViewModel, Project>(model, project);
// pass the project entity to your service layer
_projectService.Update(project);
return RedirectToAction("Index");
}
关于c# - MVC - Controller 到服务层通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9331053/