dotnet config_error ai_generated true

System.InvalidOperationException:无法为 'X' 创建 DbSet,因为已存在具有相同实体类型的 DbSet。

System.InvalidOperationException: Cannot create a DbSet for 'X' because a DbSet with the same entity type already exists.

ID: dotnet/ef-core-multiple-navigation-sets

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

版本兼容性

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

根因分析

DbContext 类定义了两个或更多映射到同一实体类型的 DbSet 属性,导致 EF Core 内部模型构建产生歧义。

English

The DbContext class defines two or more DbSet properties that map to the same entity type, causing ambiguity in EF Core's internal model building.

generic

官方文档

https://learn.microsoft.com/en-us/ef/core/modeling/entity-types

解决方案

  1. 从 DbContext 类中移除重复的 DbSet 属性。只保留一个实体类型声明。例如,移除 'public DbSet<Order> Orders { get; set; }' 或 'public DbSet<Order> SalesOrders { get; set; }' 中的一个。
  2. 如果需要多个查询接口,为不同的限界上下文使用单独的 DbContext 类。

无效尝试

常见但无效的做法:

  1. 70% 失败

    This removes the property from the context entirely, losing the ability to query that entity through that property.

  2. 50% 失败

    This duplicates code and does not solve the core issue of duplicate DbSet definitions.