Is it a good practive to return IQueryable from repositoy in .net core api

RajG 21 Reputation points
2021-10-25T13:03:40.857+00:00

Hi All,

I am writing an API with Clean Architecture in .net core with CQRS and MediatR.
My question is "Is it a good practice of returning IQueryable from repository?"
As I want to use GraphQL to provide more flexibility to UI to query data.
Please help me to understand the better approach.

Best Regards,

RK

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,134 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,626 Reputation points
    2021-10-25T14:30:04.37+00:00

    IQueryable is a leaky interface so really you should never expose it from anything you plan to test. The problem is it is pretty much impossible to properly test as every implementation is different. Even MS hasn't fully implemented it in the largest implementation they have (EF). This is perhaps the greatest pushback against OData (which people tend to need it for). Problems with it:

    • No way to properly test it as it is large and complex
    • Every implementation is different and what is supported in one (say in-memory) is not necessarily supported in another (EF)
    • No way to evaluate how the data is being queried so you can potentially build better structures and/or datasets to support the app needs
    • Possible to build queries that can easily tank your DB performance

    Outside of OData I don't know anyone who recommends every exposing this interface given the issues it is has. It is an internal interface only. Even OData folks warn to lock down this interface so bad queries aren't written but I've never seen an example of how you would do that.

    Since you plan to use GraphQL that means you are going to be exposing your query/mutators explicitly so you shouldn't need IQueryable anyway. It depends upon your approach though. Here's a starter article that may help you. Of course the challenge will be building efficient queries that don't pull back all the data and then filter and that could be a challenge.

    Personally I have yet to find a good use case for GraphQL/OData that warrants the complexity it adds. There are definite plusses but at the same time just exposing the database directly over the wire would be just as easy and have the same issues. The flexibility is awesome but giving that much power to an app seems dangerous unless you're writing pure data services. I could see this route being more appropriate if you had a reporting DB though. I also see value add when you're putting a single API over separate services (such as MS Graph).


0 additional answers

Sort by: Most helpful