使用实体框架核心设置更新时级联约束

Max*_*rty 5 entity-framework ef-core-2.1

关于在Entity Framework 核心中为外键关系设置删除动作的行为,有大量信息。但是,关于如何指定外键的“在更新级联”约束,我还没有找到几乎零的细节。

我发现的最接近的是这种迁移相关的Microsoft文档。

public void Configure(EntityTypeBuilder<Something> builder)
        {
             builder
                .HasOne(s => s.Thing)
                .WithMany(t => t.Somethings)
                .HasForeignKey(s => s.ThingId)
                --> Like Delete behavior, how to set update behavior?
                .OnDelete(DeleteBehavior.Cascade);
        }
Run Code Online (Sandbox Code Playgroud)

}

如何使用Fluent API?

Dra*_*ery 5

更新:这仍然不能解决“context.SaveChanges();”时的潜在问题 它仍然会抛出错误。您必须将数据库中的记录清空,然后重新填充它。

我一直在寻找完全相同的东西,我找到了解决方法。据我所知,目前还不能在 Fluent API 中做到这一点。您可以做的是手动将其添加到迁移中。

  1. 添加迁移
  2. 开放迁移
  3. Find the "onDelete: ReferentialAction.Cascade);"
  4. On the line above it, Insert "onUpdate: ReferentialAction.Cascade,"
  5. Update and test database
  6. See below for reference

            migrationBuilder.CreateTable(
            name: "AgencyMembers",
            columns: table => new
            {
                ApplicationUserId = table.Column<string>(maxLength: 450, nullable: false),
                AgencyId = table.Column<int>(nullable: false),
                AgencyName = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AgencyMembers", x => new { x.ApplicationUserId, x.AgencyId });
                table.ForeignKey(
                    name: "FK_AgencyMembers_AspNetUsers_ApplicationUserId",
                    column: x => x.ApplicationUserId,
                    principalTable: "AspNetUsers",
                    principalColumn: "Id",
                    ***onUpdate: ReferentialAction.Cascade,***
                    onDelete: ReferentialAction.Cascade);
                table.ForeignKey(
                    name: "FK_AgencyMembers_Agencies_AgencyId_AgencyName",
                    columns: x => new { x.AgencyId, x.AgencyName },
                    principalTable: "Agencies",
                    principalColumns: new[] { "AgencyId", "AgencyName" },
                    ***onUpdate: ReferentialAction.Cascade,***
                    onDelete: ReferentialAction.Cascade);
            });
    
    Run Code Online (Sandbox Code Playgroud)