Should a C# repository or service return IQueryable<T> to its callers, and what rule would you set for your team about where IQueryable may travel?
answer
- composable but still unexecuted
- who runs it, and when
- translation failures far from the data layer
- in-memory tests hide provider limits
basics
~20 sReturning IQueryable<T> lets callers compose filters and paging the provider runs, but hands them an unexecuted query whose cost, failures and lifetime the data layer no longer controls. Most teams keep it inside the data layer.
solid answer
~50 sThere is no single right answer; it is a trade-off between composability and control. An `IQueryable<T>` return lets a caller add `Where`, `OrderBy`, `Skip` and `Take` that the provider executes, which avoids a method per query shape. The cost is that the query has not run: it executes wherever and whenever the caller enumerates, possibly after the source it depends on is gone; any caller can write a predicate the provider cannot translate and fail at run time far from the data layer; nothing bounds how much it fetches; and tests over `AsQueryable()` accept queries the real provider rejects. A rule I would set: `IQueryable<T>` may flow inside the data-access layer and within one module that owns the source; anything crossing a module, service or process boundary takes expression filters or named parameters and returns a materialised, bounded result.
go deeper
Recall that an IQueryable<T> has not run yet: whoever enumerates it later decides when the provider executes the query.
Explain the mechanics behind the debate: callers' operators extend the tree, execution waits for enumeration, and in-memory fakes run any predicate.
Bring the production failures to the table: disposed sources at enumeration time, untranslatable predicates thrown from caller code, unbounded fetches, and double enumeration.
Own the boundary rule: where IQueryable<T> may flow, what crosses module and service lines instead, how it is enforced in review and tests, and what flexibility the team gives up.
## What IQueryable<T> in a signature promises An `IQueryable<T>` is not data. It is an expression tree plus a provider that can execute it. Returning one from a repository or service hands the caller a **query under construction**: they can add operators, and the provider runs the whole tree when someone enumerates it. That is a powerful contract, and the decision is whether your layers should offer it. ## The case for returning it - **Composability.** Callers add `Where`, `OrderBy`, `Select`, `Skip` and `Take`, and all of it reaches the provider, so filtering, projection and paging happen at the source. - **Fewer methods.** One `Query()` replaces a family of `FindByCustomerAndStatusPagedSorted` methods. - **Projection.** A caller selecting three columns fetches three columns, not whole entities. ## The case against it 1. **Execution moves to the caller.** The query runs where the caller enumerates it, possibly after the repository's unit of work, connection or context has been disposed. The failure appears in the caller's code. 2. **Translation failures escape the data layer.** The compiler accepts any expression-compatible lambda. A caller who writes `o => Rules.IsPriority(o)` gets a run-time failure from the provider, far from the code that knows its limits. 3. **No bound on cost.** A caller can enumerate the whole set, enumerate twice (running the query twice), or forget `Take`. The data layer can no longer guarantee what it runs. 4. **Tests lie.** A fake repository returning `List<T>.AsQueryable()` runs every predicate in memory with C# semantics, so tests pass for queries the real provider rejects or evaluates differently. 5. **The abstraction leaks.** Callers start writing provider-specific query code, so swapping or upgrading the provider ripples through layers that were meant not to know it. 6. **Trimming and Native AOT.** `AsQueryable()` carries IL2026 and IL3050 warnings and name-based factories such as `Expression.Property(Expression, string)` carry IL2026, a cost if the team targets AOT. ## The options between the extremes | Contract | Composable | Bounded | Provider limits stay inside | |---|---|---|---| | Return `IQueryable<T>` | fully | no | no | | Accept `Expression<Func<T, bool>>`, return a list | filters only | yes, with paging parameters | partly: callers still write predicates | | Named query methods or a query object with parameters | fixed shapes | yes | yes | | Return `IReadOnlyList<T>` or a page type | no | yes | yes | Accepting expression filters keeps execution and paging in the data layer but still lets callers write predicates the provider cannot translate. Named methods are the most controlled and the most verbose. ## Signs the current choice is hurting - Provider translation errors reported from controllers, view models or background jobs rather than from data-access code. - Pages that slow down as data grows because a caller forgot `Take`, or enumerated a returned query twice. - Tests that pass against in-memory fakes and fail against the real store. - Callers reaching for provider-specific extension methods outside the data layer. ## A rule a lead can enforce - **Inside the data-access layer**, and inside one module that owns the source, `IQueryable<T>` flows freely: composing queries there is the point. - **Across a module, service or process boundary**, signatures take parameters or `Expression<Func<T, bool>>` filters and return materialised, bounded results such as `IReadOnlyList<T>` or a page object. - **Execution happens inside the method** that owns the source's lifetime, so nothing deferred outlives it. - **Tests that check translation** run against the real provider; in-memory `AsQueryable()` fakes test logic only. - Review flags any public signature returning `IQueryable<T>` from a layer meant to hide the store, and any `IEnumerable<T>` return that is really an unexecuted query. ## How to argue it in an interview Show both sides with the mechanism behind each: `IQueryable<T>` is an unexecuted tree with a provider, so composition is cheap and control is lost. Then name the boundary where your answer changes, inside the layer that owns the provider versus across layers that should not know it, and say how the rule is enforced: signatures, review and tests against the real provider.
- A colleague says returning IEnumerable<T> instead of IQueryable<T> solves the leak. Does it?Only half. Typing the result as `IEnumerable<T>` stops callers' operators from reaching the provider, since they bind `Enumerable`. But if the object is still an unexecuted query, it runs when the caller enumerates, possibly after the source is disposed, and runs again on a second enumeration. Materialise inside the method, with `ToList()` or a page, if the goal is control.
- When is exposing IQueryable<T> across layers a reasonable choice?When the caller is meant to be a query composer and the team accepts the coupling: an internal reporting or admin module working directly against one known provider, or a framework that turns client parameters into query operators. Even then, keep a page-size cap and test against the real provider.
- Returning IQueryable<T> is always wrong, whatever layer the code sits in
- Returning IQueryable<T> runs the query inside the repository before callers see it
- Accepting Expression<Func<T, bool>> filters prevents every untranslatable predicate
- A fake repository returning List<T>.AsQueryable() proves callers' queries translate
- Typing the result as IEnumerable<T> makes an unexecuted query run inside the repository