Select projects each source element into a result shape. With EF Core, it can map database records directly to view models, so queries return only the columns the result needs. section 12.4.2
Project recipes into summary view models
A query filters deleted recipes, projects each remaining Recipe into a RecipeSummaryViewModel, and executes when ToListAsync() is called. EF Core generates the SQL and creates the view models from the returned data. section 12.4.2
Select fits into a common EF Core query flow:
- Start with a DbSet, such as _context.Recipes. section 12.4.2
- Combine Select with Where to filter records and define the result shape. section 12.4.2 section 12.4.3
- Execute with ToListAsync(), SingleAsync(), or SingleOrDefaultAsync(); EF Core translates the query and may run unsupported expressions in C# after retrieving needed fields. section 12.4.2 section 12.4.3
- Project related child objects, such as recipe ingredients, into nested view-model objects. section 12.4.3
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
Inspect the complete EF Core list query, including filtering, view-model construction, selected properties, and asynchronous execution. section 12.4.2

