dotnet data_error ai_generated true

System.InvalidOperationException:导航属性 'X' 不是映射的实体类型。考虑使用 'DbContextOptionsBuilder.EnableSensitiveDataLogging' 来查看参数值。

System.InvalidOperationException: The navigation property 'X' is not a mapped entity type. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the parameter values.

ID: dotnet/ef-core-navigation-property-not-mapped

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

版本兼容性

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

根因分析

Entity Framework Core 尝试包含一个未注册为 DbSet 或缺少外键配置的导航属性。

English

Entity Framework Core attempts to include a navigation property that is not registered as a DbSet or has missing foreign key configuration.

generic

官方文档

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

解决方案

  1. 确保导航属性的目标实体在 DbContext 中作为 DbSet 包含。例如:public DbSet<Order> Orders { get; set; }
  2. 在 OnModelCreating 中添加流式 API 配置:modelBuilder.Entity<Parent>().HasMany(p => p.Children).WithOne(c => c.Parent).HasForeignKey(c => c.ParentId);

无效尝试

常见但无效的做法:

  1. 70% 失败

    This removes the navigation property entirely, breaking the relationship query.

  2. 80% 失败

    Does not address the missing mapping; EF Core still cannot resolve the navigation.