2012-03-14 43 views
0

我使用代码先行先试延迟加载,车型如下,混淆延迟加载

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; } 
    } 

我读茱莉亚·勒曼的著作“编程实体框架”,并与懒加载混淆。当我写如下的代码,

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()将达到数据库,并返回我的价值,如果我禁用延迟加载,也不会击中数据库并将零返回给我。但无论我启用延迟加载还是禁用延迟加载,该值始终为零。我对延迟加载的理解是否错误?任何人都可以帮忙

回答

2

试着让你的球员的virtuel

public Virtual List<Player> players { get; set; } 
+0

虚拟是正确的关键字 – Tx3 2012-03-14 09:02:20

0

关于延迟加载..

在这种类型的负载,相关实体被自动加载 从数据源当您访问导航属性。通过此加载类型,请注意,如果实体尚不在ObjectContext中,则您将针对数据源 执行一个单独的查询结果的每个导航属性。

你的情况,这将意味着,playersv(TeamSet)的导航属性。如果加载单个team set,那么对于该team set,实体框架也加载players

您的代码示例可能更像是一个测试,因为查询没有.Where。如果以后你会得到数百个TeamSets那么它会导致对数据库的大量查询。

阅读this了解为什么返回零计数。