The FOREIGNKEY constraint in EF may cause loops or multiple cascading paths.
Ef, we need to pay attention when creating the foreign key, otherwise the title will appear.
Example: Project tables, project favorites tables, and user tables
The project table has the following fields: ProjectId, InputPersonId, etc.
The project favorites table has the following fields: ProjectId, UseId, etc.
The User table has the following fields: User ID, etc.
Project table:
public partial class ProjectInfoMap : EntityTypeConfiguration<ProjectInfo> { public ProjectInfoMap() { this.ToTable("ProjectInfo"); this.HasKey(pr => pr.Id); this.Property(pr => pr.Id).HasColumnName("ProjectId"); this.HasRequired(pr => pr.InputPerson) .WithMany() .HasForeignKey(pr => pr.InputPersonId); } }
Project favorites table:
public partial class ProjectCollectMap : EntityTypeConfiguration<ProjectCollect> { public ProjectCollectMap() { this.ToTable("ProjectCollect"); this.HasKey(pc => pc.Id); this.HasRequired(pc => pc.ProjectInfo) .WithMany(p => p.ProjectCollects) .HasForeignKey(pc => pc.ProjectId); this.HasRequired(pc => pc.User) .WithMany(u=>u.ProjectCollects) .HasForeignKey(pc => pc.UserId); } }
User table:
public partial class UserMap: EntityTypeConfiguration<User> { public SISTUserMap() { this.ToTable("User"); this.HasKey(u => u.Id); this.Property(u => u.Id).HasColumnName("UserId"); } }
For analysis, if a user data in the User table is deleted,
It is like a sub-join deletion, that is, when you delete a user, multiple paths can be cascade to delete the project favorite table, and an error is displayed in the title.
Delete a user-> delete a project favorite table (deleting a project also deletes the project favorite table)
Delete a user-> delete a project favorite table
The solution is as follows:
1. delete one of the cascade deletions. The Code is as follows. We do not recommend this because such mappings are not appropriate.
public partial class ProjectInfoMap : EntityTypeConfiguration<ProjectInfo> { public ProjectInfoMap() { this.ToTable("ProjectInfo"); this.HasKey(pr => pr.Id); this.Property(pr => pr.Id).HasColumnName("ProjectId"); this.HasRequired(pr => pr.InputPerson) .WithMany() .HasForeignKey(pr => pr.InputPersonId) .WillCascadeOnDelete(false); } }
2. Map InputPerson to the input user-project table, that is, associate the input user and Project id with another table. ProjectInfo Removal
this.HasRequired(pr => pr.InputPerson) .WithMany() .HasForeignKey(pr => pr.InputPersonId);
public partial class ProjectInputPersonMap : EntityTypeConfiguration<ProjectInputPerson> { public ProjectInputPersonMap() { this.ToTable("ProjectInputPerson"); this.HasKey(pc => pc.Id); this.HasRequired(pc => pc.ProjectInfo) .WithOptional(p => p.InputPerson); this.HasRequired(pc => pc.User) .WithMany() .HasForeignKey(pc => pc.UserId); } }
If the description is incorrect, please note it in the comments.