Hello, I created a console application with the entity framework. To load data using the principle of lazy load. And it works if you write like this:

Context db = new Context(); var teams = db.Teams.ToList(); foreach(Team t in teams) { Console.WriteLine("Team named is {0} ", t.Name); foreach(Player p in t.Players) Console.WriteLine("In team {0}, have player {1}", t.Name, p.Name); } Console.ReadKey(); 

That is, I am loading a list of commands in the Varovsk variable, and everything is pulled to it. And when I go through everything in the loop, all the rules, but if I load not the sheet, but iqueryable, then there is this: var teams = db.Teams; In this case, there will be an error: enter image description here

Please explain why this is happening? Why can't I get a collection of players from this kind of data?

Reported as a duplicate by participants tym32167 , 0xdb , Pavel Mayorov c # 13 Apr '18 at 8:49 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

As tym32167 correctly noted, "it is necessary to materialize a query into a collection," from raw IQueryable. Due to lazy loading, the data in IQueryable is not fully loaded until you submit them to the collection. For example in List. More details can be read here .

upd. Perhaps this code will help you:

 var players = db.Teams .Include(x=>x.Players) // включает в себя игроков (и тогда их можно прочитать из IQueryable и/или преобразовать в список) 

Or collect only players immediately in the collection:

 var players = db.Teams .SelectMany(x=>x.Players) .ToList(); 

In any case, it is not recommended to leave a request as IQueryable, for transfer to somewhere.