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

EF Core 8 TPH继承下一对多关系自动外键问题求助

EF Core 单表鉴别器模式下的外键配置问题

场景说明

我正在开发一个支持客户上传文件的网站应用,采用SQL Server数据库。部分文件是文档附件,部分是无关联的独立文件。我采用单表存储所有文件信息,通过ParentId和ParentType(鉴别器字段)实现文档到文件的一对多关联,不需要文件到父文档的自动导航属性。

核心实体代码

public class FilesFromClients
{
    public int id { get; set; } // 主键

    // 其他属性
    public int ParentId { get; set; }
    public ParentType pType { get; set; }   // 鉴别器
}

public enum ParentType : int { NOTSET = 0, SOME=1, HRMAGREEMENT=2 };

文件可以关联父文档(设置对应ParentId和ParentType),也可以是无关联状态(ParentId为0,pType=NOTSET),因此这两个属性无法设置为唯一键。

派生类与关联配置代码

public class HrmFiles : FilesFromClients {}  // 对应鉴别器类型的派生类

// 后续计划新增更多文档类型的派生类

public class NewHrmAgreement 
{
    public int Id { get; set; } // 主键

    // 其他属性
    ICollection<HrmFiles> Files { get; set; }
}

public virtual DbSet<FileFromClients> tblFiles;
public virtual DbSet<HrmFiles> hrmFiles;

// OnModelCreating 配置
modelBuilder.Entity<FileFromClient>(e =>
{
    e.HasDiscriminator<ParentType>(c => c.PType)
         .HasValue<cFileFromClient>(ParentType.NOTSET)
         .HasValue<cUploadsNoParents>(ParentType.SOME)
         .HasValue<HrmFiles>(ParentType.HRMAGREEMENT);    
});

modelBuilder.Entity<NewHrmAgreement>(e =>
{
    e.HasMany(a => a.Files)
     .WithOne()
     .HasForeignKey(f => f.ParentId);
});

问题出现过程

执行迁移时,EF Core自动生成了额外的外键:

migrationBuilder.AddForeignKey(
    name: "FK_FilesFromClients_NewHrmAgreements_ParentId",
    table: "FilesFromClients",
    column: "ParentId",
    principalTable: "NewHrmAgreements",
    principalColumn: "ID");      

由于我计划新增更多文档类型和鉴别器值,这个外键显然不必要且配置错误。更新数据库时出现报错:

Introducing FOREIGN KEY constraint 'FK_FilesFromClients_NewHrmAgreements_ParentId' on table 'FilesFromClients' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

尝试修改删除行为参数:

e.HasMany(a => a.Files) 
 .WithOne()
 .HasForeignKey(f => f.ParentId)
 .OnDelete(DeleteBehavior.ClientNoAction);

但更新数据库时仍然出现冲突错误:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_FilesFromClients_NewHrmAgreements_ParentId". The conflict occurred in database "autoabcNGTest", table "dbo.NewHrmAgreements", column 'ID'

手动移除迁移中的该外键后,所有功能正常:EF Core会自动在查询中加入ParentType过滤,数据库记录的创建和删除均符合预期。

当前困惑

我现在在两个方案间犹豫:

  • 方案一:取消NewHrmAgreement.Files的映射,手动处理关联逻辑
  • 方案二:每次生成迁移后手动移除该外键

请问我是否存在配置遗漏或错误?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:23:11