liveBook · Manning

SaveChanges

As explained in .NET in Action, Second Edition

SaveChanges is the EF Core DbContext method that persists tracked changes to the database.

SaveChanges is the DbContext operation that persists tracked additions and other changes to the database. Objects added to a DbSet remain only in application memory until the context is saved. section 5.2

Use SaveChanges when:

  • Adding entities with DbContext.Add and committing them to the configured database. section 5.2
  • Relying on EF Core to populate convention-based integer identifiers after insertion. section 5.2
  • Querying persisted data after the save operation; querying first does not return additions that exist only in code. section 5.2

Add books and persist them

using var dbContext = new CatalogContext(); dbContext.Add(new Book { Title = ".NET in Action" }); dbContext.Add(new Book { Title = "API Design Patterns" }); dbContext.SaveChanges(); foreach (var book in dbContext.Books.OrderBy(b => b.Id)) Console.WriteLine($"{book.Title} has id {book.Id}"); section 5.2

Listing 5.5 Adding Books to CatalogContext and getting ordered list
using ManningBooks;
  
using var dbContext = new CatalogContext();                  #1
dbContext.Add(new Book { Title = ".NET in Action" });        #2
dbContext.Add(new Book { Title = "API Design Patterns" });   #3
dbContext.Add(new Book { Title = "Grokking Simplicity" });
dbContext.Add(new Book { Title = "The Programmer's Brain" });
dbContext.SaveChanges();                                     #4
  
foreach (var book in dbContext.Books.OrderBy(b => b.Id))     #5
{
  Console.WriteLine($"\"{book.Title}\" has id {book.Id}");   #6
}

Shows the complete add-save-query sequence, including generated identifiers and the point at which persistence occurs. section 5.2

How .NET in Action, Second Edition covers it

How deep it goes
Explains the save boundary and generated identifiers through a focused in-memory example, without detailing transaction or change-tracking internals.
Examples
Uses a CatalogContext, Book entities, an in-memory database, generated Id values, and an ordered LINQ query.
What it assumes
Assumes familiarity with C# classes and introduces the DbContext, DbSet, entities, and convention-based keys through the example.
What you can do after
Apply it via EF Core to persist added entities and verify their generated identifiers with a subsequent query.
How it connects
Connects DbContext, DbSet, entity tracking, primary keys, generated identifiers, and LINQ queries.

Also explained in

Compare how 3 books explain SaveChanges →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.