在efcore中我在一个实体中配置了多个类型相同的一对多的约束,在迁移的时候出现
The foreign key {'LastModifierId'} on the entity type 'User' cannot have a required dependent end since it is not unique.
这个问题各位可以解决吗

efcore导航属性,codefirst迁移出现问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 港湾泊 2023-12-25 15:00关注
当你在EF Core中配置多个相同类型的一对多关系时,每个外键都需要有一个独特的名称。错误提示 The foreign key {'LastModifierId'} on the entity type 'User' cannot have a required dependent end since it is not unique. 指的是在 User 实体上有一个或多个名为 LastModifierId 的外键,并且这些外键都是必需的,但它们的名称不是唯一的。
为了解决这个问题,你需要确保每个外键的名称都是唯一的。以下是一些建议的解决方案:
- 手动指定外键名称:
在你的实体配置中,确保每个外键都有一个唯一的名称。例如:
modelBuilder.Entity<User>() .HasMany(u => u.SomeEntities1) .WithOne(e => e.User1) .HasForeignKey(e => e.LastModifierId1) .HasConstraintName("FK_User_SomeEntities1"); modelBuilder.Entity<User>() .HasMany(u => u.SomeEntities2) .WithOne(e => e.User2) .HasForeignKey(e => e.LastModifierId2) .HasConstraintName("FK_User_SomeEntities2");
- 使用不同的导航属性:
如果可能,你可以为每个外键使用不同的导航属性名称,这样EF Core会为你生成唯一的外键名称。例如:
public class User { public int Id { get; set; } public ICollection<SomeEntity> SomeEntities1 { get; set; } public ICollection<AnotherEntity> SomeEntities2 { get; set; } } public class SomeEntity { public int Id { get; set; } public int LastModifierId1 { get; set; } public User User1 { get; set; } } public class AnotherEntity { public int Id { get; set; } public int LastModifierId2 { get; set; } public User User2 { get; set; } }
使用上述模型,EF Core会自动为每个外键生成唯一的名称。
- 检查模型的其他部分:
确保你的实体模型中没有其他的配置或关系会导致冲突。
选择最适合你情况的解决方案,并应用到你的实体配置中,然后再次尝试迁移。
解决 无用评论 打赏 举报 - 手动指定外键名称: