Since 10 November 2026, .NET 11 and EF Core 11 are available as stable packages. I still build this boilerplate on EF Core 10, and the reason is a NuGet dependency. The example is a small TodoApi: one entity, one DbContext, five Minimal API endpoints, the first migration, and its way into the database as a migration bundle in a dedicated Compose service instead of Migrate() at app start. All output comes from my test on 14 November 2026 in a throwaway container (SDK 10.0.401, runtime 10.0.12, linux/arm64, 2 CPUs, 1800 MB RAM) against postgres:17-alpine.
Package state on 14 November 2026
EF Core 10 instead of 11: the dependency decides
| Package | Highest stable version | Highest version overall |
|---|---|---|
| Microsoft.EntityFrameworkCore | 10.0.15 (10.x) and 11.0.0 | 11.0.0 |
| Microsoft.EntityFrameworkCore.Design | 10.0.15 (10.x) and 11.0.0 | 11.0.0 |
| dotnet-ef | 10.0.15 (10.x) and 11.0.0 | 11.0.0 |
| Npgsql.EntityFrameworkCore.PostgreSQL | 10.0.3 | 11.0.0-rc.3 |
On the writing day the PostgreSQL provider has no stable 11 package, and its 10 package declares EF Core as [10.0.4, 11.0.0). EF Core 11 cannot be combined with it, and a release candidate does not belong in a boilerplate that people copy. On top of that, the EF Core docs list EF Core 10 as an LTS release supported until 10 November 2028 (the .NET release index gives 14 November 2028 for the 10.0 channel), while .NET 11 is an STS release. If you are still on .NET 8, the post on migrating from .NET 8 to .NET 10 covers the upgrade.
Project file and tooling
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
The provider pulls Microsoft.EntityFrameworkCore transitively; in the test NuGet resolved it to 10.0.15. The startup project needs the Design package for the tools. I pin the tool itself to the same version:
dotnet tool install --global dotnet-ef --version 10.0.15
dotnet ef --version
TodoApi: entity, context, five endpoints
Todo.cs and AppDbContext.cs
namespace TodoApi;
public class Todo
{
public int Id { get; set; }
public required string Title { get; set; } // NOT NULL
public string? Note { get; set; } // NULL allowed
public bool IsDone { get; set; }
public DateTime CreatedAtUtc { get; set; } // write Kind=Utc only
}
using Microsoft.EntityFrameworkCore;
namespace TodoApi;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Todo> Todos => Set<Todo>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Todo>(e =>
{
e.Property(t => t.Title).HasMaxLength(200);
e.Property(t => t.Note).HasMaxLength(2000);
e.HasIndex(t => t.CreatedAtUtc);
});
}
}
With nullable reference types enabled, string becomes a required column and string? an optional one; required avoids the warning about the uninitialised property.
Program.cs without Migrate() at startup
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using TodoApi;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException("Connection string 'Default' not found.");
builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(connectionString));
var app = builder.Build();
var todos = app.MapGroup("/todos");
todos.MapPost("/", async (CreateTodo input, AppDbContext db, CancellationToken ct) =>
{
var todo = new Todo { Title = input.Title, Note = input.Note, CreatedAtUtc = DateTime.UtcNow };
db.Todos.Add(todo); // Add, not AddAsync
await db.SaveChangesAsync(ct);
return TypedResults.Created($"/todos/{todo.Id}", TodoDto.From(todo));
});
todos.MapGet("/", async (AppDbContext db, CancellationToken ct, int page = 1, int pageSize = 20) =>
{
page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 1, 100);
var items = await db.Todos.AsNoTracking()
.OrderBy(t => t.Id) // unique ordering before Skip/Take
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(t => new TodoDto(t.Id, t.Title, t.Note, t.IsDone, t.CreatedAtUtc))
.ToListAsync(ct);
return TypedResults.Ok(items);
});
todos.MapGet("/{id:int}", async Task<Results<Ok<TodoDto>, NotFound>> (int id, AppDbContext db, CancellationToken ct) =>
await db.Todos.AsNoTracking().Where(t => t.Id == id)
.Select(t => new TodoDto(t.Id, t.Title, t.Note, t.IsDone, t.CreatedAtUtc))
.FirstOrDefaultAsync(ct) is { } dto
? TypedResults.Ok(dto)
: TypedResults.NotFound());
todos.MapPut("/{id:int}", async Task<Results<NoContent, NotFound>> (int id, UpdateTodo input, AppDbContext db, CancellationToken ct) =>
{
var rows = await db.Todos.Where(t => t.Id == id).ExecuteUpdateAsync(s => s
.SetProperty(t => t.Title, input.Title)
.SetProperty(t => t.Note, input.Note)
.SetProperty(t => t.IsDone, input.IsDone), ct);
return rows == 0 ? TypedResults.NotFound() : TypedResults.NoContent();
});
todos.MapDelete("/{id:int}", async Task<Results<NoContent, NotFound>> (int id, AppDbContext db, CancellationToken ct) =>
await db.Todos.Where(t => t.Id == id).ExecuteDeleteAsync(ct) == 0
? TypedResults.NotFound()
: TypedResults.NoContent());
app.Run();
public record CreateTodo(string Title, string? Note);
public record UpdateTodo(string Title, string? Note, bool IsDone);
public record TodoDto(int Id, string Title, string? Note, bool IsDone, DateTime CreatedAtUtc)
{
public static TodoDto From(Todo t) => new(t.Id, t.Title, t.Note, t.IsDone, t.CreatedAtUtc);
}
Three decisions in there: Add instead of AddAsync, because the API docs reserve the async variant for special value generators such as SequenceHiLo. Reads run with AsNoTracking and project onto a DTO so the entity never leaves the service. ExecuteUpdateAsync and ExecuteDeleteAsync write immediately and bypass the change tracker, which also means no automatic concurrency control; done manually, the docs route it through a concurrency token in the filter and the number of affected rows, which this example does not use. The CRUD responses in the test: POST 201 with Location: /todos/1, GET 200, PUT and DELETE 204, the second DELETE 404.
The first migration and its misleading error message
Connection string 'Default' not found
The EF tools execute Program.cs to obtain the context from the DI container. Without the variable set, dotnet ef migrations add InitialCreate ended like this in the test:
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Connection string 'Default' not found.
Unable to create a 'DbContext' of type 'AppDbContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[TodoApi.AppDbContext]' while attempting to activate 'TodoApi.AppDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
The second line is the prominent one and sends you looking for an IDesignTimeDbContextFactory. The cause is in the first: Program.cs throws on the missing connection string before the host is built, and the tools fall back to a parameterless constructor that AppDbContext does not have. With the variable set, the same command succeeds:
export ConnectionStrings__Default="Host=localhost;Database=todo;Username=postgres;Password=<PASSWORD>"
dotnet ef migrations add InitialCreate
# Done. To undo this action, use 'ef migrations remove'
So I did not need a factory with WebApplication.CreateBuilder, as long as Program.cs runs through to building the host. The three generated files under Migrations/ belong in the repository, snapshot included.
What the provider makes of the model
After the bundle run, \d "Todos" in psql shows:
| C# property | PostgreSQL column | Nullable |
|---|---|---|
int Id |
integer, generated by default as identity |
not null |
required string Title + HasMaxLength(200) |
character varying(200) |
not null |
string? Note + HasMaxLength(2000) |
character varying(2000) |
null |
bool IsDone |
boolean |
not null |
DateTime CreatedAtUtc |
timestamp with time zone |
not null |
Table and columns keep their capital letters. In PostgreSQL that makes double quotes mandatory: SELECT * FROM Todos is folded to todos and does not find the table.
Bundle instead of Migrate() at startup
Why not simply Migrate()
The current Microsoft docs do not rule out Migrate() at startup. Since EF Core 9 a database-wide lock protects against instances migrating in parallel, and the docs call the startup call acceptable for applications that prefer simple deployment and can tolerate startup migration behavior. Their tradeoff list also names the missing rollback, which the other strategies provide out of the box, and the risk from other applications accessing the database while it is being migrated. They recommend the separate step where review, least-privilege credentials, coordinated rollout or high availability matter. Directly below the code sample, however, a warning box remains: consider carefully before using this approach in production, prefer a bundle for automation and a SQL script where review and approval are required. The permissions argument is what convinces me: the app then only needs read and write access to the tables, and a dedicated deploy identity changes the schema. The Compose example below does not implement that separation yet; for brevity both services run as postgres there. In production, api gets its own role that may only read and write data, and only migrate uses the identity with schema permissions.
| Strategy | SQL reviewable beforehand | Lock since EF Core 9 | Schema permissions in the app |
|---|---|---|---|
Migrate() at app start |
no | yes | yes |
| Migration bundle as a separate job | no | yes | no |
| Idempotent SQL script | yes | no (runs outside EF) | no |
According to the docs the bundle is the route for automated deployments; the script is right when someone has to read, modify or archive the SQL first. The bundle's drawback is in the docs as well: it currently shows neither the SQL nor the migrations it contains. The "yes" in the lock column comes with a caveat: according to the docs the locking mechanism varies significantly across providers and can involve provider-specific issues, which is why they point to the provider's documentation.
Measured: 38 seconds, 144 MB, two runs
dotnet ef migrations bundle --self-contained -r linux-arm64 -o /tmp/efbundle
# Building bundle...
# Done. Migrations Bundle: /tmp/efbundle
The build took 38 seconds in the test (timestamps before and after the command, 2 CPUs, arm64). The single file is self-contained and, according to ls -la, 143974472 bytes, roughly 144 MB. I did not measure linux-x64. The first run against the empty database:
Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration '20261114201618_InitialCreate'.
Done.
Exit code 0. The second run reports "No migrations were applied. The database is already up to date." and also exits with 0. That repeatability is exactly what the Compose condition in the next section relies on. Without --connection and without the variable, the bundle fails with the two lines from the section above, in the bundle's case with the fully qualified type name TodoApi.AppDbContext, exit code 1: the bundle executes Program.cs too, and it already does so at build time. dotnet ef migrations bundle creates the context first to determine its type, reads only the host and database name from the connection string while doing so, and does not connect. In the test the variable from the previous section was still exported; in the Dockerfile below the build stage therefore needs a dummy value.
Compose: migrate as a one-shot service
+----------+ service_healthy +-----------+ service_completed +----------+
| db | ------------------> | migrate | --------------------> | api |
| postgres | | efbundle | _successfully | TodoApi |
+----------+ +-----------+ +----------+
services:
db:
image: postgres:17-alpine
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: todo
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d todo"]
interval: 5s
timeout: 3s
retries: 10
migrate:
build:
context: .
target: migrate
environment:
ASPNETCORE_ENVIRONMENT: Production
ConnectionStrings__Default: Host=db;Database=todo;Username=postgres;Password=${POSTGRES_PASSWORD}
depends_on:
db:
condition: service_healthy
api:
build:
context: .
target: app
environment:
# example: same role as migrate; in production use a dedicated role without schema permissions
ConnectionStrings__Default: Host=db;Database=todo;Username=postgres;Password=${POSTGRES_PASSWORD}
ASPNETCORE_HTTP_PORTS: "8080"
ports:
- "8080:8080"
depends_on:
migrate:
condition: service_completed_successfully
Per the Compose reference, service_completed_successfully waits until the service has run to successful completion; service_healthy waits for the healthcheck, here pg_isready. The migrate service deliberately has no restart key (Compose default no), because the EF docs require that the migration container is not restarted after it exits successfully; a policy such as always or unless-stopped breaks that. How healthchecks and restart policies interact is covered in the post on HEALTHCHECK and restart_policy. The matching Dockerfile follows the multi-stage pattern and is a sketch I did not build in this test:
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet tool install --global dotnet-ef --version 10.0.15
ENV PATH="$PATH:/root/.dotnet/tools"
# the bundle build runs Program.cs: dummy string for parsing only, no connection is made
ENV ConnectionStrings__Default="Host=build;Database=todo;Username=build;Password=build"
ENV ASPNETCORE_ENVIRONMENT=Production
RUN dotnet publish -c Release -o /out/app
# on arm64 hosts: -r linux-arm64
RUN dotnet ef migrations bundle --self-contained -r linux-x64 -o /out/efbundle --force
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS app
WORKDIR /app
COPY --from=build /out/app .
ENTRYPOINT ["dotnet", "TodoApi.dll"]
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0 AS migrate
WORKDIR /app
COPY --from=build /out/efbundle .
ENTRYPOINT ["./efbundle"]
The docs say a self-contained bundle runs without an installed runtime; that runtime-deps is enough for it is my inference from that. I saw the path /root/.dotnet/tools in the SDK container. The dummy connection string in the build stage applies only there; the app and migrate stages start from other base images and receive their real value from Compose. According to the docs, production secrets do not belong in an appsettings.json next to the bundle, but in a secure configuration source or in --connection. With this Program.cs, however, --connection alone is not enough according to the tools' source code (not separately verified in the test): the bundle creates the context first and sets the supplied string only afterwards, so the exception from Program.cs fires before that. That is why the migrate service sets the variable. In addition, the build stage and the migrate service set ASPNETCORE_ENVIRONMENT=Production, because the EF tools fall back to Development when no environment is set and a bundle could otherwise load development user secrets unexpectedly.
Two errors that only surface at runtime
42P01 before the migration
The app starts fine without an applied migration. Only GET /todos returns HTTP/1.1 500 Internal Server Error with an empty body, and the log says:
fail: Microsoft.EntityFrameworkCore.Query[10100]
Npgsql.PostgresException (0x80004005): 42P01: relation "Todos" does not exist
42P01 is the PostgreSQL code undefined_table. The boilerplate lacks AddProblemDetails and UseExceptionHandler, so the client only sees the empty 500. This error is the reason for the Compose ordering above: api may only start once migrate has finished.
Kind=Local instead of UTC
One line changed, CreatedAtUtc = DateTime.Now, rebuilt without a compiler warning. POST /todos then ends with 500 and:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> System.ArgumentException: Cannot write DateTime with Kind=Local to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array, range, or multirange. (Parameter 'value')
Since version 6.0 (without the legacy switch Npgsql.EnableLegacyTimestampBehavior), Npgsql writes only UTC DateTime values to timestamp with time zone; according to the Npgsql docs the column type stores no time zone, only a UTC timestamp. A side finding from the test: the POST response carries seven fractional digits (.1752648Z), the row read back six (.175264Z), because PostgreSQL stores timestamps with a resolution of 1 microsecond.
Questions about the first migration
How does CI notice that a migration is missing?
In the test, dotnet ef migrations has-pending-model-changes reported "No changes have been made to the model since the last migration." with exit code 0 when nothing had changed, and "Changes have been made to the model since the last migration. Add a new migration." with exit code 1 after a new property without a migration. As a step in the GitHub Actions workflow, that fails the build. dotnet ef database update aborts in the same state with the PendingModelChangesWarning.
Why not EnsureCreated()?
The docs say it directly: EnsureCreatedAsync and migrations do not work well together, the transition is not a seamless experience, and according to the docs the simplest way to do it is to drop the database and recreate it using migrations. As examples for EnsureCreated, the docs name prototyping, tests and local caches.
Can I get lowercase table names?
With the community plugin EFCore.NamingConventions, version 10.0.1 for EF Core 10, via UseSnakeCaseNamingConvention(). It is not an official part of EF Core, and on an existing database it produces a migration that renames everything; the README warns that this process currently involves dropping and recreating primary keys. So decide before the first migration.
Further documentation and next steps
What I add next
AddProblemDetails and UseExceptionHandler so that a 500 gets a body, and a second migration to run the has-pending-model-changes flow through CI once. If you want to set up a stack like this for a business application or move an existing EF application to PostgreSQL, I do that with you as part of my .NET development work.
Sources I opened
- Applying Migrations, bundles, lock and container section
- EF Core tools reference and Design-time DbContext creation
- Npgsql: Date and time handling
Note: The articles on this blog are produced with the help of AI and are editorially reviewed before publication. Editorial responsibility lies with Emre Yurtbay (see the legal notice).