c# - 关注点分离的 MVC 最佳实践

标签 c# asp.net-mvc scaffolding

我正在使用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/

相关文章:

c# - 如何使div可见和不可见

asp.net-mvc - ASP.Net MVC - 同时返回 View 和启动文档

c# - 在 ASP.Net MVC Core 中创建新 Controller 时,如何防止 MVC Core 添加一些不需要的包?

laravel - 最好的 Laravel 脚手架 Crud 生成器?

c# - 检查字符串的单词是否存在于字符串列表中

C# GUI 入门教程

asp.net - ASP.NET MVC 3 应用程序中每个浏览器选项卡/窗口的新 session

grails - 我是否需要在grails中实现CRUD方法?

c# - 使用 IValueConverter 类更改文本框的背景

c# - Newtonsoft.Json 引用提示 Azure Functions