【问题标题】:Entity Framework Core TPH Inheritance 2 sub Classes related to Other ModelEntity Framework Core TPH Inheritance 2 与其他模型相关的子类
【发布时间】:2020-08-15 17:09:09
【问题描述】:

我正在开发一个带有 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-core entity-framework-core


    【解决方案1】:

    是的,您可以使用流畅的 API。假设您使用的是 Table per Type (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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 2018-04-01
      • 2017-02-11
      相关资源
      最近更新 更多