I\'m using EF Model first with POCO entities and with custom DbContexts. My problem is that setting LazyLoadingEnabled=false
does not affect anything, navigatio
With the above sample, EF still loads the Programs and OwnerProgram properties of the Program class. I have tried removing the virtual keywords, disabling the proxy creation and also verified that LazyLoadingEnabled=false on the Model itself.
Am I missing something?
You need to remove default constructor that initializes these properties.
The effect you are seeing is called relationship fixup.
Actually the navigation properties are not loaded explicitly. The query _dbContext.Programs.ToList()
only loads the whole Programs
table from the database. This is just a simple SQL query (like SELECT * FROM ProgramsTable
) without any WHERE
clause and without any JOIN
to related rows.
Also no lazy loading happens here (it really can't if you disable it and if you disable even dynamic proxies) when you access the program.Programs
and program.OwnerProgram
navigation properties.
The navigation properties get populated when the result from your query is materialized because your query (that loads all programs) will have loaded all programs that the navigation properties can refer to. EF detects that those related entities are already in memory and put them into the navigation properties automatically.
You can verify this if you don't load all programs but only, for example, a single one:
Program program = _dbContext.Programs.FirstOrDefault();
Now, program.Programs
and program.OwnerProgram
will be null
- unless the loaded program
is part of its own program.OwnerProgram
collection or is its own OwnerProgram
.
"EF still loads the Programs and OwnerProgram properties of the Program class"
This is the correct behavior, but instead of loading the navigation properties lazily, it loads them eagerly.
This means that the database queries required to retrieve the navigation property values are executed immediately when the Program
entity is retrieved and the navigation properties are populated.
When LazyLoadingEnabled
is set to true
these queries aren't triggered until you attempt to access the navigation properties. This also applies to when you're hovering your mouse over navigation properties and the debugger is attached, which may lead you to think that the entities aren't being lazily loaded when in fact they are - the debugger is accessing the navigation property, so Entity Framework loads it.
You can run a SQL profiler such as this one to see exactly when queries are being triggered as you debug your code.