skip to content

In EF Core 10, what does dotnet ef dbcontext optimize generate, which startup cost does it remove, and what prevents a model from being compiled?

level: seniorimportance: nice to knowfreq 22%

answer

  1. model building on first use
  2. a RuntimeModel subclass in C#
  3. discovered without UseModel since 9
  4. EFOptimizeContext in the project file
  5. query filters are not supported

basics

~20 s

dotnet ef dbcontext optimize generates C# source for a compiled model, so EF Core loads the finished model instead of building it from conventions and OnModelCreating on the context's first use. It helps large models only, and query filters block it.

solid answer

~40 s

The first operation on a context type makes EF Core build its model: run conventions, read attributes and execute `OnModelCreating`. For hundreds or thousands of entity types that can add noticeable startup time. `dotnet ef dbcontext optimize` writes that model out as generated C# (a `RuntimeModel` subclass with an `Instance` property), which EF loads instead. Since EF Core 9 a compiled model in the context's assembly is discovered automatically, with `UseModel` still available. The source must be regenerated whenever the model changes, by hand or through the Microsoft.EntityFrameworkCore.Tasks package with `EFOptimizeContext`. Generation fails for entity types with query filters, and a custom `IModelCacheKeyFactory` only earns a warning. It does not speed up queries; `--precompile-queries` is a separate, experimental NativeAOT feature.

code

bash · 1 line
bash
dotnet ef dbcontext optimize --output-dir CompiledModels --namespace OutdoorGear.Data.CompiledModels

go deeper

for a junior

Recall that EF Core builds its model on a context's first use and that dotnet ef dbcontext optimize generates that model as C# ahead of time.

for a middle

Explain what the generated RuntimeModel replaces, how EF Core 9 and 10 discover it, and how the Tasks package keeps it regenerated.

for a senior

Show when a compiled model is worth it after measuring cold start, and which features, query filters first, rule it out for a context.

for a principal

Weigh faster cold starts against generated code, build-time coupling and lost features, and decide whether the model's size justifies it at all.

## What EF Core does on first use Creating a `DbContext` instance is cheap. The expensive step happens on the **first operation** on a context type, such as the first query or the first `Add`: EF builds the **model**, its description of every entity type, property, key, relationship and mapping. It runs the conventions, reads the data annotations, executes `OnModelCreating` and validates the result, then caches the model for the rest of the process. For a model with a few dozen entity types it is quick; for a model with hundreds or thousands of entity types it can be a visible part of startup, which hurts most in apps that scale to zero and start often. ## What a compiled model is `dotnet ef dbcontext optimize` runs that model building at **design time** and writes the result as C# source: - a class such as `GearContextModel`, deriving from `RuntimeModel`, with a static `Instance` property; - one generated file per entity type describing its properties, keys and mappings; - partial `Initialize` and `Customize` methods you can extend in your own partial class. The command takes `--output-dir`, `--namespace` and `--suffix` to place the files, plus `--precompile-queries` and `--nativeaot` for the separate query-precompilation feature. ## How EF Core finds it | EF Core version | How the compiled model is used | |---|---| | EF Core 8 and earlier | you add `UseModel(GearContextModel.Instance)` to the context's options | | EF Core 9 and 10 | a compiled model in the same assembly as the context is **discovered automatically**; `UseModel` still works | The generator also emits an assembly-level `[DbContextModel]` attribute that links the context type to its compiled model, which is what discovery relies on. ## Keeping it in sync A compiled model is a snapshot. Change an entity or `OnModelCreating` and forget to regenerate, and the app runs with the old model. Two ways to stay in sync: 1. Rerun `dotnet ef dbcontext optimize` as part of every model change, enforced in review or CI. 2. Reference **Microsoft.EntityFrameworkCore.Tasks** and set `EFOptimizeContext` to `true`. The package's `EFScaffoldModelStage` property defaults to `publish`; set it to `build` to regenerate the model on every build. ## What prevents compilation - **Query filters.** If an entity type has a filter configured with `HasQueryFilter`, generation throws: "Compiled model can't be generated, because query filters are not supported." A shop that soft-deletes products with a global filter cannot use a compiled model for that context. - **Custom constructor bindings** configured explicitly also fail; the error asks you to configure them in `Customize()` instead. - **A custom `IModelCacheKeyFactory`**, which usually means the model varies per context instance, produces a warning: the generated model is fixed, so you generate one per variant and choose at runtime. - The EF Core docs also list lazy-loading and change-tracking proxies and value converters that call private methods as unsupported. ## Compiled models versus precompiled queries A compiled model removes **model building**. It does not change how each LINQ query is translated; EF's query cache and `EF.CompileAsyncQuery` cover that. **Precompiled queries** go further, generating interceptors with finished SQL at publish time for NativeAOT, and the docs mark them experimental and not ready for production. ## A worked decision for the gear shop The shop's `GearContext` maps about forty entity types: products, variants, brands, categories, stock, orders and reviews. It also soft-deletes discontinued products with a query filter. Two facts settle the question: - With forty entity types, model building is unlikely to be the main cost of the first request; a cold-start measurement would confirm it. - The query filter would make `dotnet ef dbcontext optimize` fail for this context anyway. So the shop skips compiled models. A marketplace with two thousand entity types, deployed to instances that scale to zero, would measure first and might find model building dominating cold start; that is the case the feature was built for. ## When to bother Measure the first request after start-up with a cold process. If model building is a meaningful slice and the model is large, a compiled model helps. For a small model, the maintenance and the feature limits cost more than the milliseconds saved.

  • The shop's GearContext uses HasQueryFilter for soft-deleted products; what are your options if startup is too slow?
    Compiled-model generation throws for entity types with query filters, so that context cannot use one. Either keep the filter and accept runtime model building, or replace the global filter with explicit `Where` clauses before compiling. First confirm that model building, not connection set-up or JIT, is what makes the first request slow.
  • What happens if the model changes and nobody reruns dbcontext optimize?
    Because EF Core 9 and later discover the compiled model automatically, the app keeps using the stale generated model, so new properties or mappings are missing at runtime. Regenerate on every model change, or let Microsoft.EntityFrameworkCore.Tasks with `EFOptimizeContext` do it during the build.

  • A compiled model makes every LINQ query execute faster at runtime.
  • A compiled model updates itself automatically whenever an entity class changes.
  • dotnet ef dbcontext optimize precompiles the SQL for every query by default.
  • A context with a soft-delete HasQueryFilter compiles like any other context.
  • Since EF Core 9 a compiled model is ignored unless UseModel is called.

Assumes EF Core 10; since EF Core 9 a compiled model in the context's assembly is discovered without UseModel, and Microsoft.EntityFrameworkCore.Tasks can regenerate it on build.