3
votes

I got little confused with following scenario,

  1. I have model 'Student'
  2. I have SchoolContext class - public property DbSet Students{get;set;}
  3. Service, with following line of code

    using(var context = new SchoolContext())
    {
        var query = context.Students.Where(s => s.Gender =="M");
        var results = query.ToList();
    }
    

While debugging, I mouse hover on context.Students & expand property Results View and realized all students are already loaded irrespective of filter and after filter-where is getting applied.

I am not sure, however, I read somewhere that until pointer hits .ToList() everything remains under IQueryable. So here in this case var query supposed to be IQueryable without loading any data and just query with where condition and next line then will hit database with generated query and return only needed data.

Am I missing anything or mixing it with any other concept of EF?

2
Probably because the debugger caused it to execute - haim770
Your attached debugger is enumerating Students when you hovered over the property, in production this would not happen. - Igor
Do you mean, in actual scenario, it generates query and then loads data? Is it only causing because of debugging? - Avi Kenjale
"expand property Results View and realized all students are already loaded irrespective of filter and after filter-where is getting applied" and you completely ignored the warning saying enumerable will be expanded on click lol. If you hovered over query and did the same results would be filtered. Here you are hovering over the entire unfiltered collection (Students) - Mardoxx

2 Answers

4
votes

Your mouse over on context.Students and opening Results View force data loading from database to memory (it's needed to show you these data in debugger). So, only your mouse over is the reason. In production data will filter as expected.

1
votes

Visual Studio is loading all students for you when you are trying to see the value of non-filtered Students property in the debugger:

While debugging, I mouse hover on context.Students & expand property Results View

Everything remains under IQueryable until you try to evaluate it. It can happen when you call some method which executes query and performs a database roundtrip - ToList(), Count() etc. Or it can happen when you try to enumerate values in Visual Studio debugger.