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

时间:2018-08-01 19:40:39

标签: entity-framework ef-core-2.1

关于在实体框架核心中为外键关系设置删除操作的行为的信息很多。但是,关于如何指定 外键的“在更新级联”约束。

我发现最接近的是this与迁移相关的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);
        }

}

如何使用Fluent API做到这一点?

1 个答案:

答案 0 :(得分:1)

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

我一直在寻找完全相同的东西,但发现了解决方法。据我所知,您还不能在Fluent API中执行此操作。您可以做的是将其手动添加到迁移中。

  1. 添加迁移
  2. 开放式迁移
  3. 找到“ onDelete:ReferenceentialAction.Cascade);”
  4. 在其上方的行上,插入“ onUpdate:ReferentialAction.Cascade”,
  5. 更新和测试数据库
  6. 请参阅下文以供参考

            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);
            });