0
votes

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?

2

2 Answers

2
votes

Try to make your Player's virtuel

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

About lazy loading..

In this type of loading, related entities are automatically loaded from the data source when you access a navigation property. With this type of loading, be aware that each navigation property that you access results in a separate query executing against the data source if the entity is not already in the ObjectContext.

In your case it would mean that players is navigation property of the v (TeamSet). If single team set is loaded then Entity Framework load also players for that team set.

Your code sample is probably more like a test as there is no .Where for query. If later you would get hundreds of TeamSets then it would cause huge amount queries against database.

Read this to understand why zero count is returned.