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



在实体框架Core中有大量关于设置外键关系的删除操作行为的信息,但是,我几乎没有发现关于如何指定外键的"更新级联时"约束的详细信息。

我找到的最接近的是这份与迁移相关的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实现这一点?

Update:这仍然不能解决"context.SaveChanges((;"时仍然会引发错误的根本问题。你必须清空数据库中的记录,然后重新填充它

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

  1. 添加迁移
  2. 开放式迁移
  3. 查找"onDelete:ReferentialAction.CCascade(;">
  4. 在上面的行中,插入"onUpdate:ReferentialAction.CCascade,">
  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);
    });
    

最新更新