【发布时间】:2012-03-14 08:22:11
【问题描述】:
我先用代码测试延迟加载,模型如下,
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; }
}
上下文喜欢这样,
class testContext : DbContext
{
public DbSet<Team> teamSet { get; set; }
public DbSet<Player> playerSet { get; set; }
}
我阅读了 Julia Lerman 的书“Programing Entity Framework”,对延迟加载感到困惑。当我编写如下代码时,
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();
}
当 foreach 语句执行时,我认为 v.players.Count() 会命中数据库并返回值,如果我禁用延迟加载,它不会命中数据库并返回零给我。但无论我启用延迟加载还是禁用延迟加载,该值始终为零。我对延迟加载的理解是错误的吗?有人可以帮忙吗?
【问题讨论】:
标签: entity-framework lazy-loading