gpt4 book ai didi

c# - 数据访问层(DAL)中的LINQ查询方法

转载 作者:行者123 更新时间:2023-11-30 22:43:09 25 4
gpt4 key购买 nike

基于经典三层的项目:UI(在本题中不重要)、业务逻辑层和数据访问层。我有几个表:Customers Products Orders Users。设计应该是:

//DAL methods
public IEnumerable<Customer> GetAllCustomers()
public IEnumerable<Product> GetAllProducts()
public IEnumerable<Order> GetAllOrders()
public IEnumerable<User> GetAllUsers()
//BLL methods
public IEnumerable<Order> GetOrders(long CustomerID)
public IEnumerable<Product> GetProducts(long CustomerID)
public IEnumerable<Product> GetProducts(long OrderID)

让我感到困惑的是,我发现DAL中的所有方法都是GetAllXXXX。我不得不承认这个设计工作得很好。在 DAL 中,只有 GetAll 方法。在 BLL 中,除了对 GetAll 方法的组合操作(过滤器/连接/选择)之外,别无其他。很奇怪吗?正确的做法是什么?

最佳答案

不,这并不奇怪,事实上这与我的做法非常相似。

对我来说只有区别:

  • 我使用 IQueryable<T>而不是 IEnumerable<T> (获得延期执行)
  • 我有一个通用存储库 ( Repository<T> ):
    • IQueryable<T> Find()
    • void Add(T)
    • 等等等等

这样,我的存储库就会保持干净/简单。

所以你的 BLL 可以这样实现:

public IEnumerable<Order> GetOrders(long CustomerID)
{
Repository<Order> orderRepository = new Repository<Order>(); // should use DI here, but i digress
return orderRepository
.Find() // no query executed...
.Where(o => o.CustomerID == CustomerID) // still nothing...
.ToList(); // query executed, with BL applied! cool!
}

让 BLL 进行投影/工作/逻辑。存储库只处理 T 的持久化,不关心实际类型或任何业务逻辑。

无论如何我就是这样做的。

关于c# - 数据访问层(DAL)中的LINQ查询方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4084128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com