【问题标题】:Auto-generated FK relations in EF Core - how to made them non-nullableEF Core 中自动生成的 FK 关系 - 如何使它们不可为空
【发布时间】: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 自动推断ParentChild 之间的引用关系,并生成以下迁移,在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


    【解决方案1】:

    由于依赖实体没有引用导航属性来放置 [Required] 属性或使用 C# 8 不可为空的引用类型(例如 ParentParent?),并且没有具有不可为空类型的显式 FK 属性(例如int vs int?),剩下的唯一选择就是流畅的 API。

    关系流式 API 至少需要 正确 Has + With 对,然后在这种特殊情况下使用 IsRequired() 方法:

    modelBuilder.Entity<Parent>()
        .HasMany(e => e.Childs) // collection navigation property
        .WithOne() // no reference navigation property
        .IsRequired();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2020-12-21
      • 2017-05-09
      • 2018-12-24
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      相关资源
      最近更新 更多