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.

1

1 Answer 1

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;
    }
}
2
  • hi Luca, what if I had a Domain and Application Layer between, would I need to place EnableQuery on the middle layers also?
    – user13431554
    Jun 29, 2020 at 22:15
  • please see question here, thanks stackoverflow.com/questions/62650392/…
    – user13431554
    Jun 30, 2020 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.