ADR: Entity Framework, explained
- Status
- accepted
- Date
- 2026-09-03
- Shipped as
- 1.0.0.43
A companion to
ADR: The relational store, written for a developer meeting EF Core for the
first time. That record says what was decided and why; this one walks the
setup file by file and explains what each piece is actually doing.
It exists for the same reason ADR: Program.cs, explained does. Generated
configuration is the easiest place in a project to carry things nobody can
account for, and a data layer is the worst place for that to be true.
In plain words
This page walks through how the code talks to the database (Entity Framework Core), one file at a time, for a developer meeting it for the first time. Every generated file is explained, so nothing in the data layer is there without a reason someone can state.
What that is worth: a developer new to EF Core can change the schema safely after one read, and the organization's data layer carries no setup that nobody can account for.
The five pieces
A DbContext is a session with the database. YardDbContext is a class
that names the tables it can see and, through DbSet<T>, gives you something
you can write LINQ against. When you write db.Vehicles.Where(...), EF turns
that expression into SQL and runs it. The context also tracks the objects it
handed you so that changing one and calling SaveChanges() produces an UPDATE
for exactly the columns you touched.
A context is not thread-safe and is not meant to be long-lived. It is a unit of
work: open, do a thing, dispose.
IDbContextFactory<T> is how you get one when you are not in a request.
The usual advice for a web application is AddDbContext, which gives every
HTTP request its own context and disposes it at the end. That is the right
default and it is not what this application needs. The catalogue is read once
at startup, before any request exists, and the two sources and the bid store
are singletons that outlive every request. AddDbContextFactory registers a
factory instead, and each of them opens a context for the length of one
operation and disposes it. using var db = factory.CreateDbContext(); is that
in one line.
A migration is the schema, as code, with a history. Running
dotnet ef migrations add InitialCreate compares the model in YardDbContext
against the last known state and writes three files: the migration itself, with
an Up that creates the tables and a Down that drops them; a .Designer.cs
holding a snapshot of the model at that point; and an updated
YardDbContextModelSnapshot.cs, which is what the next migration will compare
against.
At startup, db.Database.Migrate() looks at a table called
__EFMigrationsHistory, sees which migrations have already been applied to
this particular database, and runs the ones that have not. That is the whole
mechanism, and it is why the alternative was rejected: EnsureCreated() makes
the tables and writes no history, so the second time the model changes there is
nothing to compare against and no way forward except deleting the database.
The design-time factory keeps the tooling out of the application. When
dotnet ef needs to know what the model looks like, it will by default start
your application to find a context in its service provider. That would be fine
in most projects and is actively harmful in this one: this application migrates
and seeds during startup, so generating the very first migration would boot an
app that tries to seed tables the migration has not created yet.
YardDbContextFactory implements IDesignTimeDbContextFactory<YardDbContext>,
which the tooling prefers over booting anything. It hands back a context with a
throwaway connection string, because the tooling only ever reads the model from
it.
There is a matching detail worth knowing because the error message is the only
place it is stated clearly: Microsoft.EntityFrameworkCore.Design has to be
referenced by the startup project, not only by the project holding the
context. That is what dotnet ef migrations add failed on the first time it
was run here.
Primitive collections are stored as JSON. VehicleRow.DamageNotes is a
List<string>, and EF Core maps it to a single text column holding a JSON
array. No join table, no second entity. That is the right shape for a list that
is only ever read back whole with its owner, which these two are.
The three files with the same name
Look in the directory holding the database during a run and there are three
files, not one:
SQLite is in write-ahead logging mode. A committed transaction is written to
the log and fsynced there, and moved into the database proper by a checkpoint
later, usually at a clean shutdown. That is why a database file can be 4,096
bytes, exactly one page, while holding two hundred vehicles: they are in the
log, and the next process to open the pair replays it.
Two practical consequences. Copying yard.db on its own can copy an empty
database, so the log has to come with it. And a size check on the database file
alone can report that the data vanished when it did not, which is exactly what
happened here and is written up in ADR: The relational store.
Why the row types are not the domain records
TheYard.Data.Vehicle is a sealed record with required init properties and
IReadOnlyList<string> collections. Every one of those choices is deliberate
and every one of them is awkward for a persistence layer: init-only members
cannot be set field by field after construction, and a read-only interface is
not something EF can populate.
The alternative to a second type is loosening the first one, and that trade
runs the wrong way. The domain record is used everywhere and its immutability
is load-bearing: with copies drive the bid overlay, and value equality drives
the tests. So VehicleRow is a plain mutable class, VehicleRows maps between
them in one file, and the awkwardness is confined to a mapper instead of spread
through the application.
The honest cost is in the other record: adding a field to a vehicle is now
three edits rather than one.
What AsNoTracking is doing there
By default a context remembers every entity it returns so it can work out what
changed later. That bookkeeping is worth paying for when you intend to write.
The catalogue reads never write, so AsNoTracking() tells EF to skip it. On a
few hundred rows the difference is small. It is in the code because the habit
matters more than this instance: a read path that tracks is a read path that
allocates and holds objects for no reason.
What the seed is checking, and why
YardSeed.EnsureSeeded asks whether the table is empty, not whether the file
is new. Those come apart in exactly one case that matters: a process that died
partway through its first seed leaves a database with a schema and no rows. The
emptiness check fills it on the next start. A "have I seeded before" flag would
have recorded the attempt and left the tables empty forever.
In the code
The context and its model (api/TheYard.Infrastructure/YardDbContext.cs):
protected override void OnModelCreating(ModelBuilder model)
{
base.OnModelCreating(model);
bool sqlServer = Database.IsSqlServer();
model.Entity<YardUser>().Property(user => user.Id).HasMaxLength(YardColumns.IdentityKeyLength);
model.Entity<IdentityRole>().Property(role => role.Id).HasMaxLength(YardColumns.IdentityKeyLength);
model.Entity<IdentityUserClaim<string>>().Property(claim => claim.UserId).HasMaxLength(YardColumns.IdentityKeyLength);
model.Entity<IdentityRoleClaim<string>>().Property(claim => claim.RoleId).HasMaxLength(YardColumns.IdentityKeyLength);
model.Entity<IdentityUserLogin<string>>(login =>
{
login.Property(row => row.LoginProvider).HasMaxLength(YardColumns.IdentityKeyLength);
login.Property(row => row.ProviderKey).HasMaxLength(YardColumns.IdentityKeyLength);
login.Property(row => row.UserId).HasMaxLength(YardColumns.IdentityKeyLength);
});
model.Entity<IdentityUserRole<string>>(role =>
{
role.Property(row => row.UserId).HasMaxLength(YardColumns.IdentityKeyLength);
role.Property(row => row.RoleId).HasMaxLength(YardColumns.IdentityKeyLength);
});
model.Entity<IdentityUserToken<string>>(token =>
{
token.Property(row => row.UserId).HasMaxLength(YardColumns.IdentityKeyLength);
token.Property(row => row.LoginProvider).HasMaxLength(YardColumns.IdentityKeyLength);
token.Property(row => row.Name).HasMaxLength(YardColumns.IdentityKeyLength);
});
model.Entity<VehicleRow>(vehicle =>
{
vehicle.ToTable("Vehicles");
vehicle.HasKey(row => row.Id);
vehicle.Property(row => row.Seq).IsRequired();
vehicle.HasIndex(row => row.Seq).IsUnique();
vehicle.Property(row => row.Id).HasMaxLength(YardColumns.IdLength);
vehicle.Property(row => row.Vin).HasMaxLength(17).IsUnicode(false);
vehicle.Property(row => row.Make).HasMaxLength(64);
vehicle.Property(row => row.Model).HasMaxLength(64);
vehicle.Property(row => row.Trim).HasMaxLength(64);
vehicle.Property(row => row.BodyStyle).HasMaxLength(32);
vehicle.Property(row => row.ExteriorColor).HasMaxLength(32);
vehicle.Property(row => row.InteriorColor).HasMaxLength(32);
vehicle.Property(row => row.Engine).HasMaxLength(128);
vehicle.Property(row => row.Transmission).HasMaxLength(64);
vehicle.Property(row => row.Drivetrain).HasMaxLength(16);
vehicle.Property(row => row.FuelType).HasMaxLength(32);
vehicle.Property(row => row.ConditionReport).HasMaxLength(1024);
vehicle.Property(row => row.TitleStatus).HasMaxLength(32);
vehicle.Property(row => row.Province).HasMaxLength(64);
vehicle.Property(row => row.City).HasMaxLength(64);
vehicle.Property(row => row.SellingDealership).HasMaxLength(128);
vehicle.Property(row => row.Lot).HasMaxLength(32);
if (sqlServer)
{
vehicle.Property(row => row.ConditionGrade).HasConversion<decimal>().HasPrecision(3, 1);
vehicle.Property(row => row.AuctionStart)
.HasConversion(YardColumns.AuctionStartToDateTime)
.HasColumnType("datetime2(0)");
}
});
model.Entity<PhotoRow>(photo =>
{
photo.ToTable("Photos");
photo.HasKey(row => row.File);
photo.Property(row => row.Seq).IsRequired();
photo.HasIndex(row => row.Seq).IsUnique();
photo.Property(row => row.File).HasMaxLength(128);
photo.Property(row => row.Style).HasMaxLength(32);
photo.Property(row => row.Title).HasMaxLength(256);
});
model.Entity<BidRow>(bid =>
{
bid.ToTable("Bids");
bid.HasKey(row => new { row.UserId, row.VehicleId });
bid.Property(row => row.UserId).HasMaxLength(YardColumns.IdentityKeyLength);
bid.Property(row => row.VehicleId).HasMaxLength(YardColumns.IdLength);
bid.HasOne<YardUser>()
.WithMany()
.HasForeignKey(row => row.UserId)
.OnDelete(DeleteBehavior.Cascade);
var version = bid.Property(row => row.RowVersion);
if (sqlServer)
{
version.IsRowVersion();
}
else
{
version.IsConcurrencyToken();
}
});
ActivityModel.Configure(model);
CostModel.Configure(model);
StandingsModel.ConfigureStandings(model);
CatalogueModel.ConfigureCatalogue(model, sqlServer);
BlogModel.ConfigureBlog(model, sqlServer);
LinkedInModel.ConfigureLinkedIn(model, sqlServer);
ForemanModel.Configure(model, sqlServer);
CatalogueModel.ConfigureCatalogueWords(model);
}
Live from api/TheYard.Infrastructure/YardDbContext.cs, region model, read from this build at 99df7a8.
The seed (api/TheYard.Infrastructure/Shared/Auction/EfSources.cs):
public static async Task<SeedResult> EnsureSeededAsync(YardDbContext db, IVehicleSource vehicles, IPhotoManifestSource photos, CancellationToken cancellation)
{
int vehiclesAdded = 0;
int photosAdded = 0;
if (!await db.Vehicles.AnyAsync(cancellation))
{
var rows = (await vehicles.LoadAsync(cancellation)).Select((vehicle, index) => vehicle.ToRow(index)).ToList();
db.Vehicles.AddRange(rows);
vehiclesAdded = rows.Count;
}
if (!await db.Photos.AnyAsync(cancellation))
{
var rows = (await photos.LoadAsync(cancellation))
.Select((photo, index) => new PhotoRow
{
Seq = index,
File = photo.File,
Style = photo.Style,
Title = photo.Title,
})
.ToList();
db.Photos.AddRange(rows);
photosAdded = rows.Count;
}
if (vehiclesAdded > 0 || photosAdded > 0)
{
await db.SaveChangesAsync(cancellation);
}
return new SeedResult(vehiclesAdded, photosAdded, await db.Vehicles.CountAsync(), await db.Photos.CountAsync());
}
Live from api/TheYard.Infrastructure/Shared/Stores/YardSeed.cs, region seed, read from this build at 99df7a8.
The bid store, which is the only thing here that writes
(api/TheYard.Infrastructure/Shared/Auction/EfSources.cs):
public async Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Bids.AsNoTracking().Select(row => new StoredBid(
row.UserId,
row.VehicleId,
new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
.ToListAsync(cancellation);
}
public async Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Bids.AsNoTracking().Where(row => row.VehicleId == vehicleId).Select(row => new StoredBid(
row.UserId,
row.VehicleId,
new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
.ToListAsync(cancellation);
}
public async Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync();
await using var transaction = await db.Database.BeginTransactionAsync();
if (expectedVersion is not null && !await TryMoveStandingAsync(db, vehicleId, standing, long.Parse(expectedVersion, CultureInfo.InvariantCulture), CancellationToken.None))
{
return false;
}
if (expectedVersion is null)
{
db.Standings.Add(RowOf(vehicleId, standing, version: 1));
}
await StageBuyerRowAsync(db, userId, vehicleId, state, cancellation);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return false;
}
catch (DbUpdateException) when (expectedVersion is null)
{
await transaction.RollbackAsync();
if (await StandingExistsAsync(vehicleId, CancellationToken.None))
{
return false;
}
throw;
}
await transaction.CommitAsync();
return true;
}
private static async Task StageBuyerRowAsync(YardDbContext db, string userId, string vehicleId, BidState state, CancellationToken cancellation)
{
var existing = await db.Bids.FindAsync(userId, vehicleId);
if (existing is null)
{
existing = new BidRow
{
UserId = userId,
VehicleId = vehicleId,
Amount = state.Amount,
BidCount = state.BidCount,
WonBuyNow = state.WonBuyNow,
AtMs = state.AtMs,
};
db.Bids.Add(existing);
}
else
{
existing.Amount = state.Amount;
existing.BidCount = state.BidCount;
existing.WonBuyNow = state.WonBuyNow;
existing.AtMs = state.AtMs;
}
if (db.Database.IsSqlite())
{
existing.RowVersion = Guid.NewGuid().ToByteArray();
}
}
public async Task ClearAsync(string userId, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync();
await using var transaction = await db.Database.BeginTransactionAsync();
var touched = await db.Bids.Where(bid => bid.UserId == userId).Select(bid => bid.VehicleId).ToListAsync();
await db.Standings.Where(row => touched.Contains(row.VehicleId)).ExecuteDeleteAsync();
await db.Bids.Where(bid => bid.UserId == userId).ExecuteDeleteAsync();
await transaction.CommitAsync();
}
Live from api/TheYard.Infrastructure/Shared/Auction/EfSources.cs, region bid-store, read from this build at 99df7a8.
Startup: migrate, then seed, then serve (api/TheYard.Api/Program.cs):
var seedVehicles = new JsonFileVehicleSource(dataPath);
var seedPhotos = new JsonFilePhotoManifestSource(manifestPath);
var backendList = new List<Backend>();
var firstWait = StorePrepare.FirstWaitFrom(builder.Configuration);
var sqlStartup = new StartupTimings();
var sqlState = await sqlStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => YardDatabase.PrepareAsync(yard, seedVehicles, seedPhotos, stopping), firstWait), cancellation);
var sqlBackend = new Backend
{
Key = StoreKeys.Relational,
Name = yard.Describe(),
Database = sqlState,
Startup = sqlStartup,
Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
Bids = new BidBook(new MemoryBidStore()),
Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
Probe = _ => Task.FromResult(false),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
services.GetRequiredService<YardDbContext>(),
services.GetService<IdentityErrorDescriber>()));
StoreAttachment SqlAttachment(DatabaseState state)
{
var sqlOptions = new DbContextOptionsBuilder<YardDbContext>();
yard.Configure(sqlOptions);
sqlOptions.AddInterceptors(new SqlLogInterceptor(sqlLog, currentRequest, TimeProvider.System));
var contexts = new ContextFactory(sqlOptions.Options);
var quietOptions = new DbContextOptionsBuilder<YardDbContext>();
yard.Configure(quietOptions);
var quietContexts = new ContextFactory(quietOptions.Options);
if (loggers.Factory is not null)
{
contexts.Attach(loggers.Factory);
}
relationalContexts.Hold(contexts, quietContexts);
return new StoreAttachment(
state,
new RelationalDiagnostics(contexts, yard.Describe(), () => loggers.Factory?.CreateLogger<RelationalDiagnostics>()),
Catalogues.Sql(contexts, yard, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Relational, servesBothSites)),
new BidBook(new EfBidStore(contexts)),
new EfActivityStore(quietContexts),
token => YardDatabase.HasSeedAsync(contexts, token));
}
if (sqlState.Ready)
{
sqlBackend.Attach(SqlAttachment(sqlState));
}
backendList.Add(sqlBackend);
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
cosmos = CosmosConnection.Connect(
configuredCosmos!,
builder.Configuration["Cosmos:Database"] ?? "theyard",
builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
AzureIds.ClientId(builder.Configuration),
storeLog);
cosmos.Recorder.CurrentRequest = currentRequest;
var cosmosStartup = new StartupTimings();
var cosmosState = await cosmosStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => cosmos.Starting.PrepareAsync(seedVehicles, seedPhotos, stopping), firstWait), cancellation);
var store = cosmos;
var cosmosBackend = new Backend
{
Key = StoreKeys.Document,
Name = "Azure Cosmos DB",
Database = cosmosState,
Startup = cosmosStartup,
Diagnostics = new DocumentDiagnostics(cosmos),
Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
Bids = new BidBook(new MemoryBidStore()),
Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
Probe = _ => Task.FromResult(false),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
StoreAttachment CosmosAttachment(DatabaseState state) => new(
state,
new DocumentDiagnostics(store),
Catalogues.Cosmos(store, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Document, servesBothSites)),
new BidBook(new CosmosBidStore(store)),
new CosmosActivityStore(store),
store.Starting.ProbeAsync);
if (cosmosState.Ready)
{
cosmosBackend.Attach(CosmosAttachment(cosmosState));
}
backendList.Add(cosmosBackend);
cosmosSecondChance = new StoreSecondChance.Plan(
cosmosBackend,
() => store.Starting.PrepareAsync(seedVehicles, seedPhotos, CancellationToken.None),
async state =>
{
var attachment = CosmosAttachment(state);
await attachment.Inventory.WarmAsync(CancellationToken.None);
await attachment.Bids.LoadAsync(CancellationToken.None);
cosmosBackend.Attach(attachment);
});
}
var backends = new Backends(
backendList,
defaultStore,
builder.Configuration["Peer:Site"],
siteHosts);
builder.Services.AddSingleton(siteHosts);
builder.Services.AddSingleton(backends);
builder.Services.AddScoped<CurrentBackend>();
builder.Services.AddScoped(_ =>
(relationalContexts.Contexts ?? throw new InvalidOperationException("the relational store is not attached"))
.CreateDbContext());
var secondChances = new List<StoreSecondChance.Plan>
{
new(
sqlBackend,
() => YardDatabase.PrepareAsync(yard, seedVehicles, seedPhotos, CancellationToken.None),
async state =>
{
var attachment = SqlAttachment(state);
await attachment.Inventory.WarmAsync(CancellationToken.None);
await attachment.Bids.LoadAsync(CancellationToken.None);
sqlBackend.Attach(attachment);
}),
};
if (cosmosSecondChance is not null)
{
secondChances.Add(cosmosSecondChance);
}
builder.Services.AddHostedService(services => new StoreSecondChance(secondChances, services.GetRequiredService<ILogger<StoreSecondChance>>()));
builder.Services.AddSingleton<IStoreExperiment>(
cosmos is not null ? new PartitionExperiment(cosmos, TimeProvider.System) : NoStoreExperiment.Instance);
Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region migrate-and-seed, read from this build at 99df7a8.
If you want to change the schema
These four steps were right when this record was written and are now the second
half of the job rather than the whole of it. The schema is authored as SQL first
(ADR: Data first, and the database in source control), Entity Framework maps to
it, and a conformance test fails the build if the two disagree. The full list,
in order, is in ADR: Two providers and a SQL project, explained. The short
version:
- Change the DDL in
api/TheYard.Database, with a length and a reason.
- Change the row class in
Rows.cs, and the mapping in EfSources.cs if the
field also exists on the domain record.
- Add the SQLite migration, so local development and CI get the column too:
dotnet ef migrations add <Name> --project api/TheYard.Migrations.Sqlite --startup-project api/TheYard.Api --context YardDbContext -- --sqlite
- Read the generated
Up method. It is ordinary C# and it is where the change
becomes real on SQLite.
- Commit all three generated files. The snapshot is not optional; without it
the next migration compares against the wrong model.
- Publish the SQL project with SqlPackage when it ships.
Two things in the original wording are now wrong and are worth naming rather
than deleting without a note. The migrations project is
api/TheYard.Migrations.Sqlite and not api/TheYard.Infrastructure, because
two providers produce two models and EF Core keeps one snapshot per assembly.
And "there is no step for applying it, the application does that on start" is
true of SQLite only: on SQL Server the application holds db_datareader and
db_datawriter and cannot create or alter a table at all.
Addendum, 2026-09-08: the store this record explains is one of two
Everything above explains Entity Framework, and Entity Framework is the mapper
for the relational store only. The second store, Azure Cosmos DB, is reached
through the Cosmos DB SDK directly, with no context, no migrations and no
mapper beyond a class per document and a method that copies fields
(ADR: A second store on Cosmos DB, and what it costs). If you are reading this
to learn how the deployed site on theyard.stevenstout.biz keeps its data, it
is the right record; if you are reading it to learn how the second container
keeps the same data, the newcomer's record for that side is ADR: Cosmos DB,
explained for someone who knows SQL Server, and the reason the two are
different is in the parent record.
One thing in "If you want to change the schema" changed shape: the ports the
adapters implement are asynchronous now (ADR: The ports learn to wait), so an
adapter's Load() is LoadAsync() and the calls inside it are the
...Async forms Entity Framework has always had.
Where it sits
This walkthrough explains Infrastructure code, YardDbContext and YardSeed, along with the design-time factory that now lives in the host's DesignTime.cs and the SQLite history in its own project beside the onion. The principle it teaches is single responsibility: VehicleRow changes when storage changes, the Data record Vehicle changes when the domain does, and VehicleRows is the one file that maps between them. That separation is paid for as extra edits on every new field. A team willing to let EF shape its records directly would save those edits and accept a domain record with mutable members.
Enforced by
Not machine-checked. Held by review.