asp.net-core - 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 的主键。
任何帮助将不胜感激。
解决方案
是的,您可以使用流畅的 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
推荐阅读
- python - 1000 万个大数据帧上的 for 循环的更好替代方案?
- wordpress - Query Custom Post Types & Order By Custom Post Type
- swift - 如何调整子视图控制器的高度以匹配容器视图的高度
- r - 用 R 绘制每个波长的每个/某些 PCA 分量的 R2
- c# - 如何仅在 TextBox 上填充值后才禁用保存按钮?
- visual-studio - vs2019 外部工具 unrustify 隐藏控制台
- java - 如何检查整数数组是否是螺旋排序的?
- azure-devops - 如何在 Azure DevOps 中使用自定义生成代理
- node.js - 在某些输入未填写时从表单发送数据
- c - 为什么数组值不同于赋值C程序