c# - Entity Framework 加载导航属性而不要求它们

标签 c# entity-framework navigation-properties entity-model

在一个项目中工作时,我看到了一个奇怪的行为,我无法理解加载导航属性。

这是一个重现这个“问题”的小例子。

enter image description here

我想加载一年,不包括公司的数据(导航属性)。

我的代码:

public static Year GetYear(int id)
{
    using (var context = new testModelContainer())
    {
        var result = context.YearSet.FirstOrDefault(c => c.Id == id);
        //Company test = context.CompanySet.Where(c => c.Id == id).FirstOrDefault();

        return result;
    }
}  

这会返回我想要的年份,导航属性中没有数据,但是如果我取消注释该行并且我只是执行该行,可能是因为我想知道公司名称或其他什么,它会自动包含公司数据进入年度公司导航 Assets 。

知道如何防止这种行为吗?出于安全原因,我想避免发送“ parent ”的数据。

我正在使用 EF 6、.NET 4.5。

最佳答案

这是因为您是在一个上下文中执行命令。如果在一个上下文中工作,实体会共享彼此的信息。

因此,如果您首先检索 Year,然后检索引用 Year 实体且其值为先前检索的 Year 的 Company,则您的导航属性将为自动更新,反之亦然 - Year 将填充 Company 属性。

关于c# - Entity Framework 加载导航属性而不要求它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23341655/

相关文章:

c# - 无法将类型为 'system.data.datatable' 的对象转换为类型

c# - 跟踪 Entity Framework 中删除的对象数量和类型的方法

c# - EF Core 中是否可能需要单向导航属性?

c# - Entity Framework 选择 IQueryable 抛出 "must be reducible node"

c# - 作为主键的导航属性

c# - Azure api 请求被中止 : Could not create SSL/TLS secure channel. http 客户端在调用某些 Web api 时

c# - 如何使用 Windows 窗体数据网格更新数据库? ( Visual Studio 2010)

c# - Windows Phone 8.1 按钮点击参数

c# Entity Framework 抛出异常但不回滚数据库

c# - 无法将 Entity Framework 连接到本地 SQL Server Express