【问题标题】:How to use generic repository with petapoco when querying one-to-many data查询一对多数据时如何使用带有 petapoco 的通用存储库
【发布时间】:2016-07-05 18:52:08
【问题描述】:

我正在使用通用存储库和 petapoco 微型 ORM。我将它用于 Northwind 数据库作为示例项目。由于 petapoco 不处理任何连接,因此我在 Customer 类中创建了一个列表属性。以下是我的 Repository 类的一部分

public T GetById(string id)
    {
        return this.db.SingleOrDefault<T>("WHERE CustomerId = @0", id);
    }

    public Customer GetOrdersAndCustomersByCustomerId(string id)
    {
        var customer = this.db.SingleOrDefault<Customer>("WHERE CustomerId =    @0", id);
        var orders = this.db.Query<Order>("WHERE CustomerId = @0", id).ToList();
        if (customer != null && orders != null)
        {
            customer.Orders = new List<Order>();
            customer.Orders.AddRange(orders);
        }
        return customer;
    }

虽然 GetById 使用通用变量 T,但我无法在 GetOrdersAndCustomersByCustomerId 中使用它。相反,我必须使用特定的 Customer 类。否则我无法使用这一行:customer.Orders.AddRange(orders);正如它所抱怨的那样,“T”没有“订单”的定义。有没有办法让这个方法通用?

【问题讨论】:

    标签: c# petapoco micro-orm


    【解决方案1】:

    不,这是不可能的。想一想如果您使用与Customer 不同的T 调用该方法会发生什么。这是没有意义的:

    var products = genericRepository<Product>.GetOrdersAndCustomersByCustomerId(...);
    
    // your method
    public Customer GetOrdersAndCustomersByCustomerId(string id)
    {
        var customer = this.db.SingleOrDefault<T>("WHERE CustomerId =    @0", id);
        var orders = this.db.Query<Order>("WHERE CustomerId = @0", id).ToList();
        if (customer != null && orders != null)
        {
            // what now? customer is of type product.
            customer.Orders = new List<Order>();
            customer.Orders.AddRange(orders);
        }
        return customer;
    }
    

    您可能想要的是一个非通用存储库。 IMO(很多人都同意),通用存储库不是一个好主意。如果是这样,那么已经有一个可重用的通用存储库可用了。

    我认为你最好创建一个ICustomerRepository

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2011-10-20
      相关资源
      最近更新 更多