FindAsync asynchronously loads an entity from a DbSet by its primary key. Before querying the database, it checks whether the entity is already tracked by the current DbContext and returns the tracked instance when available. section 12.4.4
Load a recipe before updating it
var recipe = await _context.Recipes.FindAsync(cmd.Id); if (recipe is null) { throw new Exception("Unable to find the recipe"); } UpdateRecipe(recipe, cmd); await _context.SaveChangesAsync(); This keeps the read, modification, and save steps explicit. FindAsync can avoid a database call when the recipe is already tracked; use a LINQ query instead when you know it is not tracked and that distinction matters. 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 FindAsync in a complete update method, including missing-entity handling and SaveChangesAsync. section 12.4.4
