A DbSet<T> represents a set of Entity Framework Core entities of type T. Expose it as a property on a DbContext to make a top-level entity available for queries and to help EF Core discover its data model. section 12.2.2 section 12.6
Listing 12.3 Defining the application DbContext
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) #1
: base(options) { } #1
public DbSet<Recipe> Recipes { get; set; } #2
}
AppDbContext exposes Recipes as a DbSet<Recipe>. EF Core also discovers Ingredient through the Recipe entity’s Ingredients property, even without a separate DbSet<Ingredient>. section 12.2.2
A DbSet is a starting point for a LINQ query. Chain operators such as Where and Select to filter and project results; an execution method such as ToListAsync then runs the query. EF Core generates SQL for the supported expressions and can fetch only the columns needed for the projection. section 12.4.2
Listing 12.7 Loading a list of items using EF Core in RecipeService
public async Task<ICollection<RecipeSummaryViewModel>> GetRecipes()
{
return await _context.Recipes #1
.Where(r => !r.IsDeleted)
.Select(r => new RecipeSummaryViewModel #2
{ #2
Id = r.RecipeId, #2
Name = r.Name, #2
TimeToCook = $"{r.TimeToCook.TotalMinutes}mins" #2
})
.ToListAsync(); #3
}
#1 A query starts from a DbSet property.
#2 EF Core queries only the Recipe columns it needs to map the view model correctly.
#3 Executes the SQL query and creates the final view models
This query excludes recipes marked as deleted and projects the results into summary view models. ToListAsync executes the query and creates the view models. section 12.4.2
To update an entity, load it through the DbSet, change its properties, and call SaveChangesAsync on the DbContext. FindAsync loads an entity by ID and checks the context’s tracked entities first. EF Core compares tracked values with their snapshots and includes changed properties in the update. section 12.4.4
Listing 12.10 Marking entities as deleted in EF Core
public async Task DeleteRecipe(int recipeId)
{
var recipe = await _context.Recipes.FindAsync(recipeId); #1
if(recipe is null) { #2
throw new Exception("Unable to find the recipe"); #2
} #2
recipe.IsDeleted = true; #3
await _context.SaveChangesAsync(); #4
}
This example finds a recipe, marks it as deleted, and saves the change. It handles a missing recipe before updating it. section 12.4.4


