Add example showing difference between directly toList or using IQueryable.
This commit is contained in:
parent
1aae643a78
commit
915434f44d
@ -1,4 +1,5 @@
|
||||
using EntityFrameworkCore.Data;
|
||||
using EntityFrameworkCore.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
using var context = new DeadBallZoneLeagueDbContext();
|
||||
@ -14,6 +15,50 @@ var teamFour = await context.Teams.SingleOrDefaultAsync(t => t.TeamId == 3);
|
||||
// Rather than raise: "System.InvalidOperationException: Sequence contains no elements."
|
||||
var coach = await context.Coaches.FirstOrDefaultAsync();
|
||||
|
||||
await ListVSIQueryableCall();
|
||||
|
||||
async Task ListVSIQueryableCall()
|
||||
{
|
||||
Console.WriteLine("Enter '1' for team with Id 1 or enter '2' for teams that contain 'Neo'");
|
||||
var option = Convert.ToInt32(Console.ReadLine());
|
||||
List<Team> teamsAsList = new List<Team>();
|
||||
// After executing ToList, the records are stored in memory.
|
||||
// Operations after that, are also done in memory.
|
||||
|
||||
teamsAsList = await context.Teams.ToListAsync();
|
||||
if (option == 1)
|
||||
{
|
||||
teamsAsList = teamsAsList.Where(t => t.TeamId == 1).ToList();
|
||||
}
|
||||
else if (option == 2)
|
||||
{
|
||||
teamsAsList = teamsAsList.Where(t => t.Name.Contains("Neo")).ToList();
|
||||
}
|
||||
foreach (var team in teamsAsList)
|
||||
{
|
||||
Console.WriteLine(team.Name);
|
||||
}
|
||||
|
||||
// Records stay as IQueryable until the ToList function is called, then the final query is performed.
|
||||
var teamsAsQueryable = context.Teams.AsQueryable();
|
||||
if (option == 1)
|
||||
{
|
||||
teamsAsQueryable = teamsAsQueryable.Where(t => t.TeamId == 1);
|
||||
}
|
||||
else if (option == 2)
|
||||
{
|
||||
teamsAsQueryable = teamsAsQueryable.Where(t => t.Name.Contains("Neo"));
|
||||
}
|
||||
|
||||
// the actual query:
|
||||
teamsAsList = await teamsAsQueryable.ToListAsync();
|
||||
|
||||
foreach (var team in teamsAsList)
|
||||
{
|
||||
Console.WriteLine(team.Name);
|
||||
}
|
||||
}
|
||||
|
||||
async Task TrackedQuery()
|
||||
{
|
||||
// EF Core tracks objects that are returned by queries.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user