DbContext and entity mapping
DbContext and entity mapping
Entity Framework Core (EF Core) maps .NET objects to database records and translates supported LINQ queries into database commands. A DbContext is a short-lived unit of work: it holds model metadata, tracks entity changes, and coordinates reads and writes through a selected database provider.
A DbSet<Book> is a query entry point and a way to register entity changes, not a loaded list. Conventions discover common keys such as Id; attributes or Fluent API can express explicit mappings. A primary key identifies a row, not a mutable display name. IsRequired configures a non-nullable column, but does not reject empty strings; validate business input separately. SaveChanges detects changes and sends commands; it does not persist every object in your process. Added, Unchanged, Modified, Deleted and Detached describe tracking, not necessarily durable database state. Use a short-lived context per unit of work; in ASP.NET Core AddDbContext normally registers it as scoped. Never run multiple concurrent operations on one context. Dispose it when finished; await operations before starting the next. The sample catalog also declares a required category relationship, unique title and revision token; later lessons explain these. The database is a fresh relational SQLite database, not the EF InMemory provider. Keep its connection open for its lifetime.
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.
Register a new entity and save it
Observe the state before and after the database write.
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 book = new Book { Title = "Orbit", Stock = 2, CategoryId = 1 };db.Books.Add(book);Console.WriteLine(db.Entry(book).State);db.SaveChanges();Console.WriteLine(db.Entry(book).State);Console.WriteLine(book.Id > 0);Console.WriteLine(db.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):
AddedUnchangedTrue3The new entity becomes tracked, then its generated key identifies a stored row. Count is a database query.
Inspect the actual model
Read the metadata for the title and key rather than guessing from the CLR declaration.
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 entity = db.Model.FindEntityType(typeof(Book))!;Console.WriteLine(entity.FindPrimaryKey()!.Properties.Single().Name);Console.WriteLine(entity.FindProperty(nameof(Book.Title))!.IsNullable);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):
IdFalseThe model requires a title value; an empty string is still a value. A database constraint and an application validation rule have distinct jobs.
Update and verify through a fresh context
Detect changes explicitly so the state observation is unambiguous.
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 book = db.Books.Single(b => b.Id == 1);book.Stock = 7;db.ChangeTracker.DetectChanges();Console.WriteLine(db.Entry(book).State);db.SaveChanges();using var verify = new Catalog(options);Console.WriteLine(verify.Books.Single(b => b.Id == 1).Stock);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):
Modified7The second context reads persisted stock rather than a cached tracked object.
Apply the concept
Add a required ISBN to the model and explain how you would validate it before saving. Describe how to confirm a new row using a fresh context.
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
DbContext and entity mapping — knowledge check
Apply the lesson concepts to the following scenarios.
What is a DbSet before enumeration?
What does IsRequired alone reject?
When is a new entity normally Added?
Can two simultaneous queries share a DbContext safely?
Why verify in another context?