我在尝试在Entity Framework Core上映射多对多关系时遇到错误,我的多对多类需要有一个额外的字段。
以下是实体:
public class RelatedProfession
{
public int ProfessionId { get; set; }
public virtual Profession Profession { get; set; }
public int SimilarProfessionId { get; set; }
public virtual Profession SimilarProfession { get; set; }
public double Similarity { get; set; }
}
public class Profession
{
[Key]
public int Id { get; set; }
public List<RelatedProfession> RelatedWith { get; set; }
public List<RelatedProfession> SimilarWith { get; set; }
}
我的fluentApi映射:
modelBuilder.Entity<RelatedProfession>()
.HasKey(p => new { p.ProfessionId, p.SimilarProfessionId });
modelBuilder.Entity<RelatedProfession>()
.HasOne(p => p.SimilarProfession)
.WithMany(p => p.SimilarWith)
.HasForeignKey(p=> p.SimilarProfessionId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<RelatedProfession>()
.HasOne(p => p.Profession)
.WithMany(p => p.RelatedWith)
.HasForeignKey(p => p.ProfessionId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Profession>()
.HasMany(p => p.RelatedWith)
.WithOne(p => p.Profession)
.HasForeignKey(p=> p.ProfessionId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Profession>()
.HasMany(p => p.SimilarWith)
.WithOne(p => p.SimilarProfession)
.HasForeignKey(p => p.SimilarProfessionId)
.OnDelete(DeleteBehavior.Restrict);
当我尝试运行时
dotnet ef migrations add xxxxx
和
dotnet ef database update
我收到以下消息错误:
引入FOREIGN KEY约束 表上的'FK_RelatedProfessions_Professions_SimilarProfessionId' 'RelatedProfessions'可能会导致循环或多个级联路径。 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他 FOREIGN KEY约束。无法创建约束或索引。看到 以前的错误。