0

Unfortunately, I have an architecture I need to follow. For my project, we have two layers: a repository layer and a service layer.

The service layer is implemented in ASP.NET Web API. I have a method that will return all orders: GetOrders(). The method will call only one method: the repository's GetOrders(), which is implemented in Entity Framework.

I've decorated the get method with the [EnableQuery] attribute, but how can I "pass" these queryable parameters to the GetOrders() in the repository layer?

Here's some code:

Service:

[EnableQuery]
public IQueryable<Order> GetOrders()
{
    return OrderRepository.GetOrders();
}

Repository:

public static class OrderRepository
{
    public static IQueryable<Order> GetOrders()
    {
        using (OrderContext context = new OrderContext())
        {
            ...
        }
    }
}

Also, the STATIC keyword is troublesome for me. Before you suggest creating a static variable of the OrderContext outside the method yet in the class, I cannot do it. My boss is a stickler for the current pattern: no static variables, etc. He wants it all contained within the method. How can I return an IQueryable, too, from the static method when I instantiate the DbContext WITHIN the method?

Thanks again, all.

Trecius Veil
  • 121
  • 8
  • Remove the `using`, i.e. don't dispose the context. See [Do I always have to call Dispose() on my DbContext objects? Nope](http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html) – Ivan Stoev Mar 29 '16 at 06:31

1 Answers1

0

You don't need to pass "anything" to the GetOrders method; you need to expose the IQueryable of your order table, and the OData will do everything for you. For example, supposing that the Orders are in the Order table:

[EnableQuery]
public IQueryable<Order> GetOrders()
{
    return OrderRepository.GetOrders();
}

public static class OrderRepository
{
    public static IQueryable<Order> GetOrders()
    {
        OrderContext context = new OrderContext()
        return context.Orders;
    }
}

Check this for more details, it's very easy and clear.

BTW, are you sure that making all the repository layer static it's a good thing? You can try something like this:

private OrderRepository _repo;

public OrderController()
{
     _repo = new OrderRepository();
}

[EnableQuery]
public IQueryable<Order> GetOrders()
{
    return _repo.GetOrders();
}

public class OrderRepository
{
    private OrderContext _context;

    public OrderRepository()
    {
        _context = new OrderContext();
    }

    public IQueryable<Order> GetOrders()
    {
        _context.Orders;
    }
}
Luca Ghersi
  • 3,261
  • 18
  • 32
  • hi Luca, what if I had a Domain and Application Layer between, would I need to place EnableQuery on the middle layers also? –  Jun 29 '20 at 22:15
  • please see question here, thanks https://stackoverflow.com/questions/62650392/net-core-how-to-send-odata-query-parameters-from-dto-to-domain-to-repository –  Jun 30 '20 at 04:45