EF Core外键配置问题代码优先问题
Posted
技术标签:
【中文标题】EF Core外键配置问题代码优先问题【英文标题】:EF Core Foreign Key configuration problem Code First Problem 【发布时间】:2022-01-01 06:28:51 【问题描述】:我在应用中有 4 个表格。
User
表(来自 IdentityUser)-UserId
是 PK
Club
表:PK 为 club_id
。
必须属于Club
的Team
表。 PK 为team_id + club_id
。
作为用户的表Player
(PK UserID
)。
必须属于一个团队的表Team_Players
:PK 为team_id + club_id + UserId
。
当我尝试添加迁移时,我收到以下错误:
具有外键属性 'Team_Id' : string 的从 'Team_Players.Team' 到 'Team' 的关系不能以主键 'Team_Id' : string, 'Club_Id' : string 为目标,因为它不兼容。为此关系配置一个主键或一组兼容的外键属性。
非常感谢您的帮助。
这是类的代码:
public class Club : BaseModel
[Display(Name = "ID")]
[Required]
[Key]
public string Club_id get; set;
public class Team : BaseModel
[Display(Name = "ID")]
[Required]
public string Team_Id get; set;
[ForeignKey("Club_Id")]
public Club Club get; set;
[Required]
[Display(Name = "Club")]
[MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
public string Club_Id get; set;
public class Player : BaseModel
[Required]
[Display(Name = "ID")]
public string UserId get; set;
[ForeignKey("Club_Id")]
public Team Club get; set;
[Required]
[Display(Name = "Club ID")]
[MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
public string Club_Id get; set;
public class Team_Players:BaseModel
[Required]
[Display(Name = "ID")]
public string UserId get; set;
[ForeignKey("Club_Id")]
public Club Club get; set;
[Display(Name = "Club ID")]
[MaxLength(50, ErrorMessage = "Field cannot be more than 50 Characters")]
public string Club_Id get; set;
[ForeignKey("Team_Id")]
public Team Team get; set;
[Display(Name = "Team ID")]
public string Team_Id get; set;
最后我的OnModelCreating
方法有以下代码:
modelBuilder.Entity<Team>()
.HasKey(e => new e.Team_Id, e.Club_Id);
modelBuilder.Entity<Coach>()
.HasKey(e => new e.UserId, e.Club_Id );
modelBuilder.Entity<Player>()
.HasKey(e => new e.UserId, e.Club_Id );
modelBuilder.Entity<Team_Players>()
.HasKey(e => new e.UserId, e.Club_Id ,e.Team_Id);
【问题讨论】:
【参考方案1】:外键以键为目标,而不仅仅是键的一部分。所以
[ForeignKey("Team_Id")]
public Team Team get; set;
应该是
[ForeignKey("Team_Id, Club_Id")]
public Team Team get; set;
因为
Entity<Team>().HasKey(e => new e.Team_Id, e.Club_Id);
【讨论】:
以上是关于EF Core外键配置问题代码优先问题的主要内容,如果未能解决你的问题,请参考以下文章
EF Core SQLite 错误 19:尽管配置了一对多,但“外键约束失败”