我正在使用MVC5制作一个网站。
我正在使用脚手架从模型类生成 Controller 。每当它创建 Controller 的支架时,数据库连接和模型操作都会在 Controller 类中发生(如下所示)。通过查看这个thread我可以看出大多数人都同意这应该发生在模型类中。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Username")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
我应该让它看起来像这样,而不是让 Controller 来做这件事吗?:
用户 Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Username")] User user)
{
if (ModelState.IsValid)
{
UserModel userModel = new userModel();
userModel.editUser(user);
return RedirectToAction("Index");
}
return View(user);
}
用户模型
public void editUser(User user){
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
要指定“db”是什么,它将是对我的数据库上下文的引用。
最佳答案
我认为您误解了您引用的答案中“模型”的含义(In a MVC application, should the controller or the model handle data access?)。
tereško 的回答指出:
The business logic in MVC and MVC-inspired patterns has to be in the model layer. And yes, model is supposed to be a layer, not a class or object.
因此,不要将数据库访问权限放入 ViewModel 中。相反,您需要业务层中有一个服务类来执行数据库访问并将数据库实体映射到数据传输对象或 View 模型。请注意我如何使用 Command 和 Query 类将对业务层的访问与 ViewModel 等任何前端类解耦(使用 AutoMapper 在 DTO <-> ViewModel <-> Command/Query 之间进行转换)。
public interface IUserService {
public UserDto CreateUser(CreateUserCommand command);
public UserDto EditUser(EditUserCommand command);
public void DeleteUser(DeleteUserCommand command);
public UserDto[] FindUsers(FindUsersQuery query);
}
Controller 使用此业务层:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserViewModel postData) {
if (!ModelState.IsValid) {
return View("Edit", postData);
}
var command = Mapper.Map<EditUserCommand>(postData);
var updatedUserDto = _userService.EditUser(command);
var updatedUserViewModel = Mapper.Map<UserViewModel>(updatedUserDto);
return View("Show", updatedUserViewModel);
}
关于c# - 关注点分离的 MVC 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50922498/