skip to content

In ASP.NET Core 10 with Microsoft.AspNetCore.OData, how do AddOData, an EDM model and AddRouteComponents expose a SalesOrders entity set through an ODataController?

level: juniorimportance: nice to knowfreq 18%

answer

  1. AddControllers().AddOData(options => ...)
  2. ODataConventionModelBuilder.EntitySet<T>(name)
  3. AddRouteComponents(prefix, IEdmModel)
  4. controller name matches entity set name
  5. UseODataRouteDebug serves ~/$odata

basics

~10 s

Chain AddOData onto AddControllers, build an IEdmModel with ODataConventionModelBuilder and EntitySet<SalesOrder>("SalesOrders"), and register it under a prefix with AddRouteComponents. A SalesOrdersController deriving from ODataController then answers /odata/SalesOrders by convention.

solid answer

~40 s

OData in ASP.NET Core is an MVC add-on, so you call `builder.Services.AddControllers().AddOData(options => options.AddRouteComponents("odata", GetEdmModel()))` and `app.MapControllers()`. The **EDM model** comes from `ODataConventionModelBuilder`: `EntitySet<SalesOrder>("SalesOrders")` declares the set and `GetEdmModel()` returns the `IEdmModel`. `AddRouteComponents` ties that model to a route prefix, so the app now serves `/odata`, `/odata/$metadata` and `/odata/SalesOrders`. A controller is matched to the set **by name**: `SalesOrdersController : ODataController` with an action named `Get` (or `GetSalesOrders`) answers the collection, and `Get(int key)` answers `/odata/SalesOrders(42)` or `/odata/SalesOrders/42`. Query options such as `$filter` and `$select` stay off until you enable them on the same options object, and `app.UseODataRouteDebug()` in Development lists every OData route at `/$odata`.

code

csharp · 15 lines
csharp
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Results;
using Microsoft.AspNetCore.OData.Routing.Controllers;

public class SalesOrdersController(SalesDb db) : ODataController
{
    // GET /odata/SalesOrders
    [EnableQuery]
    public IQueryable<SalesOrder> Get() => db.SalesOrders.AsNoTracking();

    // GET /odata/SalesOrders(42) and /odata/SalesOrders/42
    [EnableQuery]
    public SingleResult<SalesOrder> Get(int key) =>
        SingleResult.Create(db.SalesOrders.Where(o => o.Id == key));
}

go deeper

for a junior

Recall the three calls in order: AddControllers().AddOData, an EDM model from ODataConventionModelBuilder with EntitySet<T>(name), and AddRouteComponents with a prefix. Then a controller named after the entity set.

for a middle

Explain how the controller name is resolved against entity sets, which action names and the key parameter map to which URLs, and that query options are off until enabled on ODataOptions.

for a senior

Show you can debug a 404 OData route with UseODataRouteDebug, keep it out of production, and reason about prefixes, multiple models and the per-route service container.

for a principal

Be ready to argue whether an OData surface earns its place next to plain endpoints: it ties URLs and metadata to the EDM, has no Native AOT support, and makes the model a public contract.

## What the pieces are **OData** is a convention for exposing data over HTTP where the client shapes the query through URL options such as `$filter`, `$select` and `$top`. In ASP.NET Core it ships as the NuGet package **`Microsoft.AspNetCore.OData`** (9.5 at the time of writing; the package targets `net8.0` and runs in a `net10.0` app). It is built on MVC controllers, not on a separate server, so everything below rides on the normal controller pipeline. Three pieces have to line up: | Piece | API | What it does | |---|---|---| | Service registration | `AddControllers().AddOData(...)` | Adds the OData formatters, routing conventions and `ODataOptions` to MVC | | The model | `ODataConventionModelBuilder` -> `IEdmModel` | Describes entity types, keys and entity sets; the service publishes it as `$metadata` | | The route | `ODataOptions.AddRouteComponents(prefix, model)` | Binds one model to one URL prefix, with its own internal service container | The **EDM** (Entity Data Model) is OData's schema. `ODataConventionModelBuilder` reads your CLR classes by convention — the library's own samples rely on an `Id` property being picked up as the key — and turns public properties into the model's properties, so the EDM ends up describing exactly the CLR types you register. ## Program.cs for a sales-orders feed ```csharp using Microsoft.AspNetCore.OData; using Microsoft.OData.Edm; using Microsoft.OData.ModelBuilder; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<SalesDb>(); builder.Services.AddControllers().AddOData(options => options .AddRouteComponents("odata", GetEdmModel()) .Select().Filter().OrderBy().Count().SetMaxTop(500)); var app = builder.Build(); if (app.Environment.IsDevelopment()) app.UseODataRouteDebug(); app.MapControllers(); app.Run(); static IEdmModel GetEdmModel() { var model = new ODataConventionModelBuilder(); model.EntitySet<SalesOrder>("SalesOrders"); return model.GetEdmModel(); } ``` `AddRouteComponents` has overloads without a prefix (the model is served at the root), with an `ODataBatchHandler`, and with an `Action<IServiceCollection>` for services that only that route's OData container sees. Calling it twice with two prefixes and two models gives two independent OData services in one app. ## How a controller finds its entity set Routing is **convention-based**. At startup the OData application-model provider takes every controller's name without the `Controller` suffix (unless the controller is marked `[ODataIgnored]`) and resolves it against the model's entity sets and singletons. Deriving from `ODataController` is the usual choice because it adds OData attribute routing and helpers, but the name is what the conventions match. Then, for `SalesOrdersController`: 1. An action named `Get` or `GetSalesOrders` with no key parameter maps to `GET ~/odata/SalesOrders`, and also to `~/odata/SalesOrders/$count`. 2. An action with a parameter named `key` maps to the single entity: `GET ~/odata/SalesOrders(42)`, and for a single key also `~/odata/SalesOrders/42`. 3. `Post`, `Put`, `Patch` and `Delete` follow the same pattern for writes. 4. `ODataController` carries `[ODataAttributeRouting]`, and `ODataOptions.EnableAttributeRouting` defaults to `true`, so `[HttpGet("odata/SalesOrders/Open")]`-style attribute routes work beside the conventions. If the names do not line up — `OrdersController` against an entity set called `SalesOrders` — the controller is just an ordinary MVC controller and the OData URL returns 404. The quickest diagnosis is `app.UseODataRouteDebug()`, middleware that renders every OData endpoint at `~/$odata` (or at a pattern you pass it). Keep it to Development. ## What you get without writing code - `GET /odata` returns the **service document** listing the entity sets. - `GET /odata/$metadata` returns the CSDL XML of the EDM model; client generators read it. - Responses are OData JSON: a collection comes back as `{ "@odata.context": ..., "value": [ ... ] }` rather than a bare array. ## What is still off `AddOData` alone does not let clients query. The global switches on `ODataOptions.QueryConfigurations` — `EnableFilter`, `EnableSelect`, `EnableExpand`, `EnableOrderBy`, `EnableCount`, `EnableSkipToken` — all start `false`, and the global `MaxTop` starts at `0`. You turn them on with the fluent methods `Select()`, `Filter()`, `OrderBy()`, `Expand()`, `Count()`, `SkipToken()` and `SetMaxTop(n)`, or all at once with `EnableQueryFeatures(maxTopValue)`; the alternative is per-type settings carried by the model itself, such as the model builder's `[Filter]` attribute. The action itself also needs `[EnableQuery]` before any option is applied to its result. ## Limits worth knowing - **Native AOT:** the ASP.NET Core docs list OData among the features not supported under Native AOT, alongside MVC itself. - **Minimal APIs:** the package also has an `AddOData(Action<ODataMiniOptions>)` overload on `IServiceCollection`, with `WithODataResult()` and `AddODataQueryEndpointFilter()` for `MapGet` endpoints, but the controller route above is the main, fully featured path. - **One model per prefix:** the prefix is part of every generated `@odata.context` and next link, so changing it later changes URLs clients have stored.

  • Your SalesOrdersController returns data at /api/SalesOrders but /odata/SalesOrders is 404. What do you check first?
    That the controller's name minus `Controller` exactly matches an entity set in the model passed to `AddRouteComponents` (the conventions match names, not base classes), that the action is named `Get` or `GetSalesOrders`, and that the prefix is right. Then turn on `app.UseODataRouteDebug()` in Development and open `/$odata`: if the action is not listed with an OData template, the convention did not match it.
  • When would you call AddRouteComponents more than once?
    When one app serves two independent OData services, for example `AddRouteComponents("odata/sales", salesModel)` and `AddRouteComponents("odata/hr", hrModel)`. Each prefix gets its own model and its own internal service container, so `$metadata` differs per prefix and the overload taking `Action<IServiceCollection>` can register services for one route only.

  • AddOData alone lets clients use $filter and $select on every action
  • Any controller name works as long as the action has [EnableQuery]
  • OData runs as its own middleware server beside MVC, not through controllers
  • UseODataRouteDebug is safe to leave on in production
  • AddRouteComponents infers the EDM from the DbContext, so no model is needed