实体框架7在表上引入外键约束可能导致循环或多个级联路径

时间:2016-10-14 19:15:35

标签: c# entity-framework-core

这个问题与EF Core有关。

当我'更新数据库'时,我收到此错误:

Introducing FOREIGN KEY constraint 'FK_PupilTests_Tests_TestId' on table 'PupilTests' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

我理解为什么我会收到该错误,并尝试通过正确设置DeleteBehavior来删除错误,但它只是不起作用。

那么我的流畅配置有什么问题?

流畅的配置:

builder.Entity<Test>().HasMany<PupilTest>(x => x.PupilsTests).WithOne(p => p.Test).HasForeignKey(p => p.TestId).OnDelete(DeleteBehavior.Restrict);

builder.Entity<Pupil>().HasMany<PupilTest>(x => x.PupilsTests).WithOne(p => p.Pupil).HasForeignKey(p => p.PupilId).OnDelete(DeleteBehavior.Restrict);

模型

public class Pupil
{
    public Pupil()
    {
        PupilsTests = new HashSet<PupilTest>();

    }

    public int Id { get; set; }
    public ISet<PupilTest> PupilsTests { get; set; }
}


public class PupilTest
{
    public int PupilId { get; set; }
    public int TestId { get; set; }
    public decimal Scores { get; set; } 
    public Pupil Pupil { get; set; }
    public Test Test { get; set; }
}

public class Test
{
    public Test()
    {
        PupilsTests = new HashSet<PupilTest>();
    }

    public int Id { get; set; }        
    public ISet<PupilTest> PupilsTests { get; set; }

}

移植

 public partial class Init11 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_PupilTests_Pupils_PupilId",
                table: "PupilTests");

            migrationBuilder.AddForeignKey(
                name: "FK_PupilTests_Pupils_PupilId",
                table: "PupilTests",
                column: "PupilId",
                principalTable: "Pupils",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_PupilTests_Pupils_PupilId",
                table: "PupilTests");

            migrationBuilder.AddForeignKey(
                name: "FK_PupilTests_Pupils_PupilId",
                table: "PupilTests",
                column: "PupilId",
                principalTable: "Pupils",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);
        }
    }

0 个答案:

没有答案