dotnet data_error ai_generated true

System.InvalidOperationException: 导航属性 'NavigationName' 为 null。必须使用 Include 或其他预先加载方法加载相关数据。

System.InvalidOperationException: A navigation property 'NavigationName' is null. Related data must be loaded using Include or other eager loading methods.

ID: dotnet/ef-core-navigation-property-null-after-include

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2023-03-15首次发现

版本兼容性

版本状态引入弃用备注
6.0 active
7.0 active
8.0 active
9.0 active

根因分析

Entity Framework Core 导航属性为 null,因为在查询后未使用 .Include() 或 .ThenInclude() 预先加载相关数据。

English

Entity Framework Core navigation property is null because related data was not eagerly loaded with .Include() or .ThenInclude() before accessing it after a query.

generic

官方文档

https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager

解决方案

  1. 添加 .Include() 和 .ThenInclude() 以加载嵌套导航属性。示例:var orders = context.Orders.Include(o => o.Customer).ThenInclude(c => c.Address).ToList();
  2. 查询后使用 .Collection().Load() 或 .Reference().Load() 进行显式加载。示例:var order = context.Orders.First(); context.Entry(order).Collection(o => o.OrderItems).Load();
  3. 通过安装 Microsoft.EntityFrameworkCore.Proxies 并配置启用延迟加载:optionsBuilder.UseLazyLoadingProxies(); 确保导航属性为 virtual。

无效尝试

常见但无效的做法:

  1. Adding .Include() to the query but missing .ThenInclude() for nested navigation properties 75% 失败

    EF Core requires explicit .ThenInclude() for second-level navigation properties; only Include() loads the immediate property but not its children.

  2. Using .Load() after the query without calling .Collection() or .Reference() correctly 60% 失败

    Explicit loading with .Load() requires specifying the navigation property via .Collection() or .Reference() first; incorrect syntax leads to same null error.

  3. Setting LazyLoadingEnabled = true in DbContext but not installing the Microsoft.EntityFrameworkCore.Proxies package 80% 失败

    Lazy loading requires both configuration and the Proxies NuGet package; missing the package causes no automatic loading and null navigation properties.