1

On this page of the Entity Framework Core documentation, it says when querying loaded data:

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.

This is true whether it is Eager or Explicit.

I find this to be frustrating, because it will return partial data, which makes it seem like a complete list because there's nothing indicating that it is partial.

Example:

Say I have the following two classes:

class User {
    int Id { get; set; }
    string Name { get; set; }
    List<Message> Messages { get; set; }
}

class Message {
    int Id { get; set; }
    List<User> Users{ get; set; }
}

And I query using the following code:

_dbContext.Users
    .Include(u => u.Messages)
    .Single(u => u.Id == 1);

My output is the following:

"user" {
    "id": 1,
    "name": "Alice",
    "messages": [
        {
            "id": 1,
            "users": [
                {
                    "id": 1,
                    "name": "Alice",
                }
            ]
        }
    ]
}

I would expect that unless I also added .ThenInclude(m => m.Users), it would give me a null or empty list, not a partial list.

bdrelling
  • 830
  • 1
  • 10
  • 27
  • 1
    Possible duplicate of [How can I prevent EF7 from eagerly fixing up navigation properties?](http://stackoverflow.com/questions/35438600/how-can-i-prevent-ef7-from-eagerly-fixing-up-navigation-properties) – Dustin Kingen Feb 18 '17 at 04:23
  • @Romoku I don't really know how this would be a duplicate of that issue. – bdrelling Feb 22 '17 at 20:29

1 Answers1

0

I assume from your example that Alice's message with id 1 is linked to more that one user (herself).

I am not sure it is necessary to change this behavior. As you mentioned, we should use .ThenInclude(m => m.Users) if we need the navigation property to be fully initialized.

I would expect that unless I also added .ThenInclude(m => m.Users), it would give me a null or empty list, not a partial list.

The partial result will be a good thing when lazy loading will be implemented. If the navigation property you will want to access is already loaded, then you will save a round trip to the database.

Guillaume S.
  • 1,515
  • 1
  • 8
  • 21