asp.net-mvc - 我应该在哪里使用 ToList() 执行查询 - 在 DAL、BLL 还是在 Controller 中?

标签 asp.net-mvc n-tier-architecture

我有项目 DAL、BLL 和 Web。我应该在哪里使用 ToList() 执行查询?

现在我在 Controller 中使用 ToList() 执行查询 - 可以吗?例如 - 从一开始:

DAL - 我在 NotesRepository 类中的方法:

public IQueryable<Notes> GetAllNotes()
{
    return context.Notes.Include(x => x.Comments).OrderByDescending(x => x.CreateDate);
}

BLL - 我在 NotesService 类中的方法:

public IEnumerable<Notes> GetNotes()
{
    return _unitOfWork.NotesRepository.GetAllNotes();
}

Web - 我在 Controller 中的操作(使用 ToList() 执行查询):

public ActionResult Index()
{
    var notes = _notesService.GetNotes().ToList();

    return View(notes);
}

最佳答案

在我个人看来,这是一个数据问题,因此调用 .ToList() 的决定应该在 DAL 中进行。可能需要灵活地将事物链接在一起或优化查询,因此您可以证明将调用放入 BLL 中是合理的,但无论如何您都将这种灵活性构建到 DAL 中,并且总体上 DAL 返回数据,而不是查询对象。

这在现实生活中并没有发生过,但这也让您能够更灵活地将 DAL 替换为其他数据源(例如 Web api)。如果将 IQueryable 注入(inject)到 DAL 中,就会变得更加困难,并且层/层封装会被破坏。

我不建议让 IQueryable 进入 Controller 。

关于asp.net-mvc - 我应该在哪里使用 ToList() 执行查询 - 在 DAL、BLL 还是在 Controller 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534680/

相关文章:

javascript - 空字符串传递给 jquery.unobtrusive-ajax.js 中的 getElementById() :16

asp.net-mvc - 有没有办法在 .cshtml 文件中显示行号?

c# - 如何将多个参数传递给 View ?

javascript - 外部 Javascript 中的 Razor 语法

c# - WCF N 层应用程序中的异常处理和日志记录

c# - System.Web.Routing.RouteCollection 和 System.Web.Mvc.RouteCollectionExtensions 都具有相同的简单名称 'IgnoreRouteInternal'

.net - 最佳实践 : 3-Tier Architecture in LINQ

domain-driven-design - 定时任务应该放哪一层?

asp.net-mvc - Web API 在典型的 n 层架构中处于什么位置?