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


