首页 > 解决方案 > Entity Framework Core TPH Inheritance 2 与其他模型相关的子类

问题描述

我正在开发一个带有 Entity Framework Core 的 Asp.Net Core 3 应用程序。

我对继承有疑问,我不知道如何完成我需要的。

我的模型:

public abstract class Person
{
   public int Id {get; set;}
   public string name {get; set;}
}

public class Renter: Person
{
   public string address{get; set;}
   public ICollection<Invoice> Invoices{get;set;}
}

public class UserProfile: Person
{
   public string BankAccount {get;set;}
   public ICollection<Invoice> Invoices{get;set;}
}

public class Invoice
{
   public DateTime Date {get;set;}

   public Renter Renter {get; set;}
   
   [Required]
   public int RenterId {get; set;}

   public UserProfile UserProfile{get; set;}
   
   [Required]
   public int UserProfileId {get; set;}
}

现在我得到一个数据库异常:外键约束失败:RenterId References Person.Id。我可以使用 Fluent Api 手动配置我的设置吗?问题是 Invoice 需要 Renter 和 UserProfile,但 Person.Id 是 Renter 和 UserProfile 的主键。

任何帮助将不胜感激。

标签: asp.net-core.net-coreentity-framework-core

解决方案


是的,您可以使用流畅的 API。假设您使用的是按类型表 (TPT):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Renter>().ToTable("Renter");
  modelBuilder.Entity<UserProfile>().ToTable("UserProfile");
}

参见:https ://www.entityframeworktutorial.net/code-first/inheritance-strategy-in-code-first.aspx


推荐阅读