为什么我的 EF Core 迁移会忽略模型的 OnDelete 设置?
Why does my EF Core migration ignore the model's OnDelete settings?
我在尝试配置外键的 OnDelete
行为时使用了以下代码,但似乎徒劳无功:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Gender)
.WithMany()
.HasForeignKey(e => e.GenderId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Title)
.WithMany()
.HasForeignKey(e => e.TitleId)
.OnDelete(DeleteBehavior.Restrict);
}
然而,当我生成第一个迁移时,它创建了这个表和另外两个表,它为 Contact
创建了约束,如下所示:
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => x.Id);
table.ForeignKey(
name: "FK_Contact_Gender_GenderId",
column: x => x.GenderId,
principalTable: "Gender",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_Contact_Title_TitleId",
column: x => x.TitleId,
principalTable: "Title",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
在不可为 null 的列 GenderId
上,SetNull
在哪里? Cascade
可能是默认设置,忽略了我的配置。
按照@bricelam 的建议,我提交了一个问题,并在不到 24 小时内得到了正确的回复。 Microsoft 的 Smit Patel 建议:
In your project.json
you have reference to
Microsoft.EntityFrameworkCore.Commands
which was deprecated a while
ago and should be removed.
我删除了它,重新生成的迁移现在具有两个 FK 的正确 onDelete
值。
我在尝试配置外键的 OnDelete
行为时使用了以下代码,但似乎徒劳无功:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Gender)
.WithMany()
.HasForeignKey(e => e.GenderId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Title)
.WithMany()
.HasForeignKey(e => e.TitleId)
.OnDelete(DeleteBehavior.Restrict);
}
然而,当我生成第一个迁移时,它创建了这个表和另外两个表,它为 Contact
创建了约束,如下所示:
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => x.Id);
table.ForeignKey(
name: "FK_Contact_Gender_GenderId",
column: x => x.GenderId,
principalTable: "Gender",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_Contact_Title_TitleId",
column: x => x.TitleId,
principalTable: "Title",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
在不可为 null 的列 GenderId
上,SetNull
在哪里? Cascade
可能是默认设置,忽略了我的配置。
按照@bricelam 的建议,我提交了一个问题,并在不到 24 小时内得到了正确的回复。 Microsoft 的 Smit Patel 建议:
In your
project.json
you have reference toMicrosoft.EntityFrameworkCore.Commands
which was deprecated a while ago and should be removed.
我删除了它,重新生成的迁移现在具有两个 FK 的正确 onDelete
值。