I use code first to test lazy loading, models as below,
class Team
{
public int ID { get; set; }
public string Name { get; set; }
public string Boss { get; set; }
public string City { get; set; }
public List<Player> players { get; set; }
public Team()
{
players = new List<Player>();
}
}
class Player
{
public int ID { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public int Age { get; set; }
public Team team { get; set; }
}
and context likes this,
class testContext : DbContext
{
public DbSet<Team> teamSet { get; set; }
public DbSet<Player> playerSet { get; set; }
}
I read Julia Lerman's book "Programing Entity Framework", and got confused with lazy loading. When I write the code as below,
using (var context = new testContext())
{
//context.Configuration.LazyLoadingEnabled = false;
//var teams = from t in context.teamSet.Include(p=>p.players) select t;
var teams = from t in context.teamSet select t;
foreach (var v in teams)
{
Console.WriteLine(v.players.Count());
}
Console.Read();
}
When foreach statement is executed, I think v.players.Count() will hit the database and return me the value, and if I disabled lazy loading, it will not hit the database and return zero to me. But no matter I enabled lazy loading or disabled lazy loading, the value always zero. Is my understanding of lazy loading wrong? Anyone can help?