Entity Framework Core navigation properties over-eagerly loading

c# entity-framework-core npgsql


I'm just starting to play with EF core (using NPGSQL), and have noticed some strange behavior on how navigation properties are being loaded without expressly using an 'include'. An example I'm seeing:


ObjectA->List ObjectB | ObjectA->List ObjectC

ObjectB->List ObjectD

All of the navigation properties are set up, and there are items of each type in the database.

I run a query on ObjectA without any includes, so the nav properties should be empty. That's not the case; depending on the query, sometimes one of them will be filled in without an explicit include (not both, just ObjectB or ObjectC). If I do the explicit include, they both show up, like expected. This is annoying, but not the really bad problem I'm seeing.

Say I query an ObjectC. If I have all the nav properties set up, it loads ObjectA as expected, but now ObjectA also has ALL of its nav properties loaded as well; not just what relates to ObjectC, either. ALL of ObjectA's children (and their children) come back as well. This leads to hundreds of items coming back that have absolutely no relation to what was requested.

This is code-first (I'm creating the DB by hand though since scaffolding in NPGSQL seems very buggy). Here's an example of how the parent relationship is modeled for one of my entities:

  .HasOne<User>(c => c.User)
  .WithMany(p => p.Addresses)
  .HasForeignKey(c => c.UserId)
  .HasConstraintName<User, Address>("fk_addresses_user");

If I query a single Address, the parent User is pulled back, but under that every single other Address tied to the User as well (this is a single level association, but if Address had any children they would all be pulled back as well).

I'm at a loss right now; the only thing I've been able to do is remove all child nav properties from my model.

8/24/2016 6:52:46 PM

Popular Answer

I 'think' I see what it's doing now. It's auto including other properties that are already being tracked locally (which makes sense, I guess). My testing I was reading/creating several items at once, and I was confused by some things being filled in without an explicit include. After more testing, it's behaving as I expect when I have simpler queries not accessing other entities in the same context

8/25/2016 8:02:29 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow