我可以阻止Entity Framework Core用部分数据填充结果吗? [英] Can I stop Entity Framework Core from populating my result with partial data?

查看:72
本文介绍了我可以阻止Entity Framework Core用部分数据填充结果吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实体框架的此页面上核心文档,它在查询已加载的数据时说:

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


Entity Framework Core会将导航属性自动修复为以前加载的任何其他实体进入上下文实例。因此,即使您未明确包含导航属性的数据,如果先前已加载某些或所有相关实体,也可能仍会填充该属性。

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.

我发现这很令人沮丧,因为它将返回 partial 数据,这看起来像是一个完整的列表,因为没有任何表明它的数据

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.

示例

说我有以下两个类:

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; }
}

我使用以下代码查询:

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

我的输出如下:

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

I会期望除非我也添加 .ThenInclude(m => m.Users),否则它将给我一个空列表或空列表,而不是部分列表。

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.

推荐答案

在您的示例中,我认为ID为1的爱丽丝消息与一个用户(她自己)相关联。

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

我不确定是否有必要更改此行为。如您所提到的,如果我们需要完全初始化导航属性,则应使用 .ThenInclude(m => m.Users)

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.


我希望除非我也添加.thenInclude(m => m.Users),否则
会给我一个空列表或空列表,而不是部分列表

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.

这篇关于我可以阻止Entity Framework Core用部分数据填充结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆