You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用EF Core迁移无法创建InactiveUsers新表的问题排查

问题原因

EF Core 默认采用 TPH(每个层次结构一张表) 的继承映射策略,会将整个继承体系中的所有实体字段合并到基类对应的表(也就是你的Users表)中,所以才会出现InactiveUserId被加到Users表,而非生成独立的InactiveUsers表的情况。

解决方法

要让InactiveUser生成独立的表,需要显式配置 TPT(每个类型一张表) 继承策略,在DbContext的OnModelCreating方法中为InactiveUser指定单独的表名:

修改后的OnModelCreating代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().Property(t => t.Id)
        .ValueGeneratedOnAdd()
        .HasDefaultValueSql("NEWSEQUENTIALID()");

    // 配置InactiveUser映射到独立的InactiveUsers表
    modelBuilder.Entity<InactiveUser>().ToTable("InactiveUsers");
}

重新生成迁移并执行后,EF Core会创建InactiveUsers表,该表包含User类的所有字段(Id、Name、Gender)以及InactiveUser自身的InactiveUserId字段,同时原Users表结构保持不变。

如果你的需求是让InactiveUsers表与Users表结构完全一致(不需要额外的InactiveUserId),只需删除InactiveUser类中的InactiveUserId属性,再按上述方式配置表映射即可。

内容的提问来源于stack exchange,提问作者user989988

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:05:46