【问题标题】:confused with lazy loading与延迟加载混淆
【发布时间】: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


    【解决方案1】:

    努力让你的球员成为美德

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

    【讨论】:

      【解决方案2】:

      关于延迟加载..

      在这种类型的加载中,自动加载相关实体 访问导航属性时从数据源获取。有了这个 加载类型,请注意您使用的每个导航属性 访问导致针对数据源执行单独的查询 如果实体尚未在 ObjectContext 中。

      在您的情况下,这意味着 playersv (TeamSet) 的导航属性。如果加载了单个 team set,则实体框架也会为该 team set 加载 players

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 2018-03-17
        • 1970-01-01
        相关资源
        最近更新 更多