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

痞子三分冷 提交于 2019-12-02 17:13:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42310340/can-i-stop-entity-framework-core-from-populating-my-result-with-partial-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!