关于在实体框架核心中为外键关系设置删除操作的行为的信息很多。但是,关于如何指定 外键的“在更新级联”约束。
我发现最接近的是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做到这一点?
答案 0 :(得分:1)
更新:这仍然不能解决“ context.SaveChanges();”时的潜在问题。它仍然会引发错误。您必须使数据库中的记录为空,然后重新填充它。
我一直在寻找完全相同的东西,但发现了解决方法。据我所知,您还不能在Fluent API中执行此操作。您可以做的是将其手动添加到迁移中。
请参阅下文以供参考
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);
});