【发布时间】:2020-01-18 12:11:14
【问题描述】:
我有以下型号:
public class Child
{
public int Id { get; set; }
}
public class Parent
{
public int Id { get; set; }
public List<Child> Childs { get; set; }
}
在没有任何进一步指示的情况下,EF Core 3.1 自动推断Parent 和Child 之间的引用关系,并生成以下迁移,在Child 表上创建可为空的外键列:
....
migrationBuilder.CreateTable(
name: "Child",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ParentId = table.Column<int>(nullable: true) // <--- !!
},
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.Restrict);
});
导致以下架构:
我需要 FK 不可为空。如何在不更改模型的情况下强制执行 EF(无需引入仅用于定义底层存储关系的人工属性)?
PS:特别是我想通过引入2路引用来避免滥用模型,只是为了能够表达我需要的东西,例如
public class Child
{
public int Id { get; set; }
public Parent Parent { get; set; } // <--- not acceptable
}
modelBuilder.Entity<Parent>()
.HasMany(p => p.Childs)
.WithOne(c => c.Parent)
.IsRequired(); // <--- non-null
手动干预迁移代码是唯一的解决方案吗(不会导致与模型快照不匹配)?
【问题讨论】:
标签: .net-core entity-framework-core domain-driven-design entity-framework-core-migrations entity-framework-core-3.1