Entity framework 与延迟加载混淆
我首先使用代码测试延迟加载,模型如下Entity framework 与延迟加载混淆,entity-framework,lazy-loading,Entity Framework,Lazy Loading,我首先使用代码测试延迟加载,模型如下 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; }
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; }
}
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()将命中数据库并返回值,如果我禁用延迟加载,它将不会命中数据库并返回零。但无论我启用了延迟加载还是禁用了延迟加载,该值始终为零。我对延迟加载的理解是错误的吗?有人能帮你吗?试着让你的球员成为真正的明星
public Virtual List<Player> players { get; set; }
公共虚拟列表玩家{get;set;}
关于延迟加载
在这种加载类型中,会自动加载相关实体
当您访问导航属性时,从数据源。用这个
加载类型,请注意
access会导致对数据源执行单独的查询
如果实体不在ObjectContext中
在您的例子中,这意味着players
是v
(团队集)的导航属性。如果加载了单个团队集
,则实体框架也会加载该团队集的玩家
您的代码示例可能更像是一个测试,因为没有用于查询的。Where
。若以后您将获得数百个团队集
,那个么它将导致对数据库的大量查询
阅读以了解返回零计数的原因
public Virtual List<Player> players { get; set; }