我有项目 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/