skip to content

With [EnableQuery] in ASP.NET Core OData, what changes when an action returns a materialized List<SalesOrder> instead of an EF Core IQueryable, and what risks remain?

level: middleimportance: should knowfreq 26%

answer

  1. deferred execution versus rows already loaded
  2. enumerable.AsQueryable() means LINQ to Objects
  3. the client's URL becomes your query
  4. do not dispose the DbContext inside the action
  5. SingleResult.Create for one entity

basics

~20 s

A List means every row was already read and [EnableQuery] filters and pages it in memory; an IQueryable lets the options compose into one database query. Clients still shape that query, so limits and a trimmed EDM remain necessary.

solid answer

~50 s

`EnableQueryAttribute` applies options to whatever the action returns. If it is an `IQueryable`, `ApplyQuery` adds `Where`, `OrderBy`, `Skip`, `Take` and a `$select` projection to the expression, and EF Core runs **one** query when the formatter enumerates it. If it is a `List<SalesOrder>`, the filter wraps it with `AsQueryable()` and the same operators run **in memory** — the results look right, but the action has already loaded the whole table. So return `db.SalesOrders.AsNoTracking()` and, for one entity, `SingleResult.Create(query)`. Risks remain: clients now decide the shape of your SQL, an expression the provider cannot translate fails only when the result is enumerated, every EDM property is queryable, and a `DbContext` created with `using` inside the action is disposed before the deferred query runs. Limits and a read-model EDM handle the first and third; DI-scoped contexts handle the last.

code

csharp · 4 lines
csharp
// Before: reads every row, then EnableQuery filters the list in memory.
[EnableQuery(PageSize = 200)]
public async Task<List<SalesOrder>> Get() =>
    await db.SalesOrders.ToListAsync();

go deeper

for a junior

Remember to return the IQueryable from an [EnableQuery] action; a list means the whole table is read and filtered in memory.

for a middle

Explain deferred execution: EnableQuery composes onto the returned expression in OnActionExecuted and the formatter enumerates it, which also explains the DbContext lifetime rule.

for a senior

Name what an IQueryable still exposes: client-shaped SQL, late translation failures, every EDM column, and the double-application trap with ODataQueryOptions<T>.

for a principal

Judge when the explicit ODataQueryOptions<T> path is worth its code, for tenant filters or auditing, versus the attribute's automatic validation.

## Where the work happens `[EnableQuery]` does not fetch data. It takes the value your action returns and applies the request's OData options to it in `OnActionExecuted`. What that value **is** decides where the work happens: | Action returns | What EnableQuery does | Where filtering runs | Rows read from the database | |---|---|---|---| | `IQueryable<SalesOrder>` from EF Core | Composes `Where`/`OrderBy`/`Skip`/`Take`/projection onto the expression tree | In the database, as one SQL statement | Only the page asked for | | `List<SalesOrder>` from `ToList()` / `ToListAsync()` | Calls `AsQueryable()` on the list and composes the same operators | In memory (LINQ to Objects) | The whole table, before the filter starts | | `SingleResult<SalesOrder>` | Applies `$select`/`$expand` to the one-row query | In the database | One row | In the source, the non-queryable branch is literally `(enumerable as IQueryable) ?? enumerable.AsQueryable()`. Both paths produce the same JSON, which is why the list version survives code review and then falls over in production once the table grows. ## Why the list version is so tempting - An async action wants `await db.SalesOrders.ToListAsync()`, and returning an `IQueryable` feels like returning something unfinished. - Code copied from a non-OData endpoint already materialises. - A repository returns `IEnumerable<T>` or `IReadOnlyList<T>` and hides the `IQueryable`. The fix is to let the composed query stay deferred: `public IQueryable<SalesOrder> Get() => db.SalesOrders.AsNoTracking();`. The OData output formatter enumerates the result after the action returns, still within the request, so a `DbContext` registered with `AddDbContext` (scoped to the request) is alive when the query runs. `AsNoTracking()` avoids building change-tracking entries for rows that are only serialized. ## Risks that remain with an IQueryable Returning the queryable moves the work to the database, and with it the cost: 1. **The client writes your WHERE and ORDER BY.** Any filterable, sortable property in the EDM can appear in a query the database must plan. Unless you page and cap — `PageSize`, `MaxTop`, `AllowedOrderByProperties`, `MaxNodeCount` — a single URL can sort millions of rows on an unindexed column. 2. **Untranslatable expressions fail late.** Composition succeeds, but if EF Core cannot translate part of the expression it throws when the query is enumerated during serialization. Restrict functions with `AllowedFunctions` and test the queries the client will really send. 3. **Everything in the EDM is exposed.** If the model is built from the EF Core entity, `$select=CostPrice,InternalNote` works. Register a read-model type with only the public columns, or ignore properties when building the model. 4. **Lifetime of the context.** `using var db = new SalesDb(...)` inside the action disposes the context when the action returns, *before* the formatter enumerates the deferred query, so the request fails with an `ObjectDisposedException`. Inject the scoped context instead. 5. **Applying options twice.** If the action takes an `ODataQueryOptions<SalesOrder>` parameter and calls `ApplyTo` itself, do not also put `[EnableQuery]` on it; the filter would apply the options again over the shaped result. ## The explicit alternative When you need to see the options before they reach the query — to add a tenant filter, log the shape, or enforce a rule the attributes cannot express — accept `ODataQueryOptions<SalesOrder>` as a parameter instead of using `[EnableQuery]`: ```csharp // in SalesOrdersController(SalesDb db, ICurrentTenant tenant) : ODataController public IActionResult Get(ODataQueryOptions<SalesOrder> options) { options.Validate(new ODataValidationSettings { MaxTop = 500 }); IQueryable query = options.ApplyTo(db.SalesOrders.AsNoTracking() .Where(o => o.TenantId == tenant.Id)); return Ok(query); } ``` `Validate` throws on a disallowed query and `ApplyTo` returns the composed `IQueryable`, still deferred. You trade the attribute's automatic 400 for full control over the order of operations. ## A short checklist - Return `IQueryable<T>` (or `SingleResult<T>` for a key lookup), never a materialised list, from an `[EnableQuery]` action. - Use the request-scoped `DbContext`, with `AsNoTracking()` for reads. - Page and cap every queryable action. - Expose a read model in the EDM, not the full entity. - Choose either `[EnableQuery]` or `ODataQueryOptions<T>.ApplyTo` per action, not both. - Watch the logs for the SQL a typical client URL produces before the endpoint ships; the shape of that statement, not the C# in the action, is what the database pays for. None of this is specific to sales orders: any entity set behind `[EnableQuery]` has the same two failure modes — work done too early in memory, or work handed to the database without a fence around it.

  • Why does a key lookup return SingleResult<SalesOrder> rather than the entity itself?
    `SingleResult.Create(db.SalesOrders.Where(o => o.Id == key))` keeps the lookup as an `IQueryable`, so `[EnableQuery]` can still compose `$select` and `$expand` into the database query before it runs. Returning a loaded entity would apply them in memory, and with `$expand` the related rows would have to be loaded already.
  • Why does using var db = new SalesDb(...) inside an [EnableQuery] action break the request?
    The action returns a deferred `IQueryable`. The filter composes it and the formatter enumerates it after the action has returned, by which point the `using` declaration has disposed the context. The query then throws `ObjectDisposedException`. A context injected from DI is scoped to the request and is disposed only after the response is written.

Returning a List is photocopying the whole filing cabinet and then searching the copies at your desk; returning an IQueryable is handing the archive clerk a written request, so only the matching folders ever leave the cabinet.

  • Returning a List is fine because EnableQuery still turns the filter into SQL
  • Calling ToListAsync() first makes the OData endpoint faster because it is async
  • With an IQueryable, OData limits are unnecessary because the database filters
  • A DbContext created with using in the action is safe for a deferred OData query
  • $select hides columns, so exposing the full EF Core entity in the EDM is harmless