SaveChanges persists changes tracked by an Entity Framework Core DbContext to its configured database. Updating an entity typically means loading it, changing its properties, and calling SaveChangesAsync(). section 12.4.4
EF Core tracks loaded entities and keeps snapshots of their property values. When SaveChanges runs, it compares the current entity with the snapshot, includes changed properties in the UPDATE statement, and ignores unchanged properties. section 12.4.4
Updating a recipe
Find the recipe, change its Name or TimeToCook values, then call await _context.SaveChangesAsync(). EF Core generates SQL for the changed values and persists the update. section 12.4.4
Listing 12.9 Updating an existing entity with EF Core in RecipeService
public async Task UpdateRecipe(UpdateRecipeCommand cmd)
{
var recipe = await _context.Recipes.FindAsync(cmd.Id); #1
if(recipe is null) { #2
throw new Exception("Unable to find the recipe"); #2
} #2
UpdateRecipe(recipe, cmd); #3
await _context.SaveChangesAsync(); #4
}
static void UpdateRecipe(Recipe recipe, UpdateRecipeCommand cmd) #5
{ #5
recipe.Name = cmd.Name; #5
recipe.TimeToCook = #5
new TimeSpan(cmd.TimeToCookHrs, cmd.TimeToCookMins, 0); #5
recipe.Method = cmd.Method; #5
recipe.IsVegetarian = cmd.IsVegetarian; #5
recipe.IsVegan = cmd.IsVegan; #5
} #5
Shows the complete update flow in RecipeService, including entity lookup, property changes, and the final SaveChangesAsync call. section 12.4.4
SaveChanges also persists test data when using an in-memory SQLite database. Creating a separate DbContext afterward verifies that the data was written to the provider rather than merely cached by the first context. section 36.4


