Relationships and migrations
Relationships and migrations
A relationship connects a dependent row to a principal row through a foreign key. In the catalog, many books can reference one category. A migration records an intentional schema change; it is not a request-time data update.
The scalar CategoryId stores the reference; Category and Books are navigation properties for accessing related objects. A required dependent must reference a principal, but the principal need not have any books. Optional relationships permit a null foreign key. One-to-one adds uniqueness; many-to-many usually uses a join table. DeleteBehavior.Restrict prevents silent database deletion of dependents; review actual provider constraint and tracked-state behavior. EF conventions can discover relationships, but explicit configuration makes cardinality and delete policy visible. Migrations compare the current model against the previous model snapshot, generate Up and Down operations, and record applied versions in a history table. For a real change, use a reviewed project with Microsoft.EntityFrameworkCore.Design and compatible dotnet-ef tooling: add a migration, inspect the generated code and SQL script, test on a disposable copy, back up data and plan rollout and recovery. Down can drop data; it is not a backup. Review the starting migration state, generated SQL and upgrade compatibility with both old and new application versions. A migration lock does not guarantee that application traffic can safely continue during a schema change. Test schema upgrades with representative synthetic existing data and verify recovery separately. SQLite can require table rebuilds for schema changes. EnsureCreated is only used for these fresh labs; do not combine it with a migrations-managed database. The third example inspects proposed operations without applying them.
Baseline: .NET 10 / C# 14, Microsoft.EntityFrameworkCore.Sqlite 10.0.15 (published package, restore and advisory checks pending). Each independent project includes its own complete source and project file. In an approved environment with a reviewed SDK and packages, restore from approved sources, then run dotnet build --no-restore and dotnet run --no-build in the fixture directory. Except for the migration-operation inspection, each uses its own open SQLite in-memory connection, synthetic catalog and schema created by EnsureCreated. No external database, account or credential is required. Expected results are reasoned, not executed.
Connect a new category and its book
Use a navigation to express a relationship before a generated key exists.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var category = new Category { Name = "History" };category.Books.Add(new Book { Title = "Maps", Stock = 2 });db.Categories.Add(category);db.SaveChanges();var book = category.Books.Single();Console.WriteLine(book.CategoryId == category.Id);Console.WriteLine(book.Category == category);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
TrueTrueRelationship fixup connects the navigation and foreign key. EF inserts the principal before its dependent.
Reject an orphan row
SQLite foreign key enforcement is explicit in the connection string. Insert a book whose category does not exist.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();db.Books.Add(new Book { Title = "Orphan", CategoryId = 999 });try { db.SaveChanges(); }catch (DbUpdateException) { Console.WriteLine("rejected"); }using var verify = new Catalog(options);Console.WriteLine(verify.Books.Count());class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
rejected2The database rejects an invalid reference. Dispose or repair the failed context rather than reusing its pending insert blindly.
Inspect a reversible schema operation
A tiny handwritten migration-operation fixture uses no database. A real scaffolded migration includes metadata and a snapshot.
using Microsoft.EntityFrameworkCore.Migrations;using Microsoft.EntityFrameworkCore.Migrations.Operations;var migration = new AddSubtitle { ActiveProvider = "Microsoft.EntityFrameworkCore.Sqlite" };var up = (AddColumnOperation)migration.UpOperations.Single();var down = (DropColumnOperation)migration.DownOperations.Single();Console.WriteLine($"{up.Table}.{up.Name}:{up.IsNullable}");Console.WriteLine($"{down.Table}.{down.Name}");class AddSubtitle : Migration { protected override void Up(MigrationBuilder m) => m.AddColumn<string>(name: "Subtitle", table: "Books", nullable: true); protected override void Down(MigrationBuilder m) => m.DropColumn(name: "Subtitle", table: "Books");}Expected output (not executed):
Books.Subtitle:TrueBooks.SubtitleAdding a nullable column avoids requiring a value for existing rows; dropping it loses any new subtitle values. This only inspects the operation objects, not generated SQL or database migration execution.
Apply the concept
Design a change that adds a mandatory publisher relationship to existing books without losing records. List rollout stages and rollback risks.
Use the manual practice and knowledge check to reason about the boundary. Do not apply these examples to a production database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Relationships and migrations — knowledge check
Apply the lesson concepts to the following scenarios.
Which value identifies a book’s category in the database?
Does a required relationship require a category to have a book?
What does the model snapshot represent?
Why avoid EnsureCreated on a migrations-managed database?
What is a safe response to an invalid foreign key insert?