Asp.net 使用服务层关注点的核心分离

Asp.net core separation of concern using service layer

我对设计我的服务层并在我的控制器中使用它们的最佳方法有什么疑问。这是我的担忧。

目前我正在使用它来删除类别

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Delete(List<Guid> ids)
    {
        if(ids == null || ids.Count == 0)
            return RedirectToAction("List");

        _categoryService.DeleteCategories(_categoryService.GetCategoryByIds(ids));
        _categoryService.SaveChanges();

        return RedirectToAction("List");
    }

我担心的是我是否应该只将 ID 传递给 DeleteCategories,然后在 DeleteCategories 中调用 GetCategoryByIds。如果我只想删除 1 个类别,是否最好添加另一种方法,如 DeleteCategory 然后在控制器中检查 id 的长度,如果它只有 1,请改用 DeleteCategory

my concern is should I just pass ids to DeleteCategories then call the GetCategoryByIds inside the DeleteCategories.

只需将 ID 传递给 DeleteCategories 方法。我什至懒得在里面调用 GetCategoryByIds 。如果您只是打算删除类别信息,则无需查询数据库以获取所有其余类别信息。

And If I'm only going to delete 1 Category, is it better to add another method like DeleteCategory then in the controller check the length of the ids and if it is only 1, use DeleteCategory instead

我不会费心去创建另一种方法。您可以只传递一个包含一个值的列表。没有什么是 DeleteCategory 方法可以做的,而您已经无法使用 DeleteCategories.

这完全取决于您的业务逻辑

如果用户可以选择 select 多个类别并立即删除它们,那么让 delete 方法接受 ID 列表并将它们全部删除是有意义的,如果用户可以的话只删除一个类别,那么应该是DeleteById(int categoryId).

至于调用GetCategoryByIds,仍然取决于你的逻辑,如果你有某种授权,那么你必须先检索类别,确保用户有权删除提供的类别并继续如果一切顺利的话。

关于你的代码的注意事项,你的服务应该将数据操作逻辑封装在里面,你不应该公开 SaveChanges 方法并将控制权交给控制器来调用它,或者至少实现工作单元模式,如果你需要实现某种事务。