Can I stop Entity Framework Core from filling my result with partial data?

In this Core Entity Framework documentation page , she says when requesting uploaded data:

Entity Framework Core automatically corrects the navigation properties for any other objects that were previously loaded into the context instance. Therefore, even if you do not explicitly include data for the navigation property, the property can still be populated if some or all of the related objects were previously loaded.

This is true whether it is Eager or Explicit .

I believe this is disappointing because it will return partial data, which makes it look like a complete list, because nothing indicates its partiality.

Example:

Let's 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 request using the following code:

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

My conclusion is as follows:

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

I would expect that if I had not added .ThenInclude(m => m.Users), it would give me an empty or empty list, not a partial list.

0
source share
1 answer

I assume from your example that Alice's message with identifier 1 is associated with more than one user.

I am not sure that this behavior needs to be changed . As you mentioned, we should use .ThenInclude(m => m.Users)it if we need the navigation property to fully initialize.

I would expect that if I had not added .ThenInclude (m => m.Users) yet, this would give me an empty or empty list, not a partial list.

, . , , , .

0

Source: https://habr.com/ru/post/1670233/


All Articles