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

- **ID:** `dotnet/ef-core-navigation-property-null-after-include`
- **领域:** dotnet
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 6.0 | active | — | — |
| 7.0 | active | — | — |
| 8.0 | active | — | — |
| 9.0 | active | — | — |

## 解决方案

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。
   ```

## 无效尝试

- **Adding .Include() to the query but missing .ThenInclude() for nested navigation properties** — EF Core requires explicit .ThenInclude() for second-level navigation properties; only Include() loads the immediate property but not its children. (75% 失败率)
- **Using .Load() after the query without calling .Collection() or .Reference() correctly** — Explicit loading with .Load() requires specifying the navigation property via .Collection() or .Reference() first; incorrect syntax leads to same null error. (60% 失败率)
- **Setting LazyLoadingEnabled = true in DbContext but not installing the Microsoft.EntityFrameworkCore.Proxies package** — Lazy loading requires both configuration and the Proxies NuGet package; missing the package causes no automatic loading and null navigation properties. (80% 失败率)
