How to use generic repository with petapoco when querying one-to-many data

568 views Asked by At

I am using a generic repository along with petapoco micro ORM. I am using it against the Northwind database as a sample project. Since petapoco doesn't handle any joins, I have created a list property in the Customer class. The following is part of my Repository class

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;
    }

While the GetById uses the generic variable T, I am unable to use it in the GetOrdersAndCustomersByCustomerId. Instead I have to use the specific Customer class. Otherwise I am unable use this line: customer.Orders.AddRange(orders); as it complains, "T" doesn't have a definition of "Orders". Is there anyway to make this method generic?

1

There are 1 answers

0
Kenneth On BEST ANSWER

No, that's not possible. Think about what would happen if you would call the method with a different T than Customer. It wouldn't make sense:

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;
}

What you probably want is a non-generic repository. IMO (and a lot of people agree), generic repositories are not a good idea. If they were, there would already be a single reusable generic repository available.

I think you're better of creating an ICustomerRepository.