MVC分离关注点的最佳实践

CodeQuest

我正在使用MVC5制作网站。

我正在使用脚手架从模型类生成控制器。每当它创建控制器的支架时,db-connection和model-manipulation就会在控制器类内发生(请参见下面)。通过查看此线程,我可以看出大多数人都同意这应该在模型类中发生。

[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);
}

我应该让控制器看起来像这样,而不是让控制器这样做:

用户控制器

[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”是什么,它将是对我的数据库上下文的引用。

乔治·帕切德

我认为您在所引用的答案中误解了“模型”的含义(在MVC应用程序中,控制器或模型应该处理数据访问吗?)。

捷列斯科州的答案是:

MVC和受MVC启发的模式中的业务逻辑必须在模型层中。是的,模型应该是一个,而不是一个类或对象。

因此,请勿将数据库访问权限放入ViewModel中。相反,您需要在业务层中进行数据库访问并将数据库实体映射到数据传输对象或ViewModel的服务类。请注意,我如何使用Command和Query类将对业务层的访问与诸如ViewModels之类的任何前端类分离(使用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);
}

控制器使用以下业务层:

[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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章