在子实体上设置外键时,如下所示:
modelBuilder.Entity<Child>()
.HasOne(c => c.Parent)
.WithMany(p => p.Children)
.HasForeignKey(c => c.ParentId)
.OnDelete(DeleteBehavior.Cascade);
我能够配置约束的“删除时”行为。结果迁移看起来像这样:
migrationBuilder.CreateTable(
name: "Child",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ParentId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Child", x => x.Id);
table.ForeignKey(
name: "FK_Child_Parent_ParentId",
column: x => x.ParentId,
principalTable: "Parent",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
在生成的迁移中,我可以直接编辑 onUpdate 行为,如方法签名中所示:
public virtual OperationBuilder<AddForeignKeyOperation> ForeignKey(
[NotNull] string name,
[NotNull] Expression<Func<TColumns, object>> column,
[NotNull] string principalTable,
[NotNull] string principalColumn,
[CanBeNull] string principalSchema = null,
ReferentialAction onUpdate = ReferentialAction.NoAction,
ReferentialAction onDelete = ReferentialAction.NoAction);
但我无法找到通过流畅的 API 或属性来做到这一点的方法。
是否可以为外键配置 EF Core“更新时”行为?
炎炎设计
相关分类