[英]Entity Framework DB-First, implement inheritance
I'm trying to implement inheritance using entity framework 6.0 and database first approach. 我正在尝试使用实体框架6.0和数据库第一种方法实现继承。 OK, let's say I have a Person
and an Organization
entity like below: 好吧,假设我有一个Person
和一个Organization
实体,如下所示:
// a simplified version of organization entity
public class Organization
{
public Guid ID { get; set; }
public string Nickname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string OfficialName { get; set; }
public Guid CEOID { get; set; }
public DateTime? RegisterDate { get; set; }
}
// a simplified version of person entity
public class Person
{
public Guid ID { get; set; }
public string Nickname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public Guid PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string NationalCode { get; set; }
public DateTime? BirthDate { get; set; }
}
I can create these two tables in database, but I want to use inheritance so the fields which is repeated in both Person
and Organization
could be in another base class like below: 我可以在数据库中创建这两个表,但是我想使用继承,因此在Person
和Organization
重复的字段可以在另一个基类中,如下所示:
public class Identity
{
// These fields are the common fields between Person and Organization
public Guid ID { get; set; }
public string Nickname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
How can I achieve this in db-first approach? 如何在db-first方法中实现这一目标?
One possible way is to use one table for each type called TPT (table-per-type), which I prefer to use. 一种可能的方法是为每种类型使用一个表 ,称为TPT (table-per-type),我更喜欢使用它。 To achieve this, you define your tables like the model shown in the following picture: 为此,您可以像下图所示的模型一样定义表:
Note that the relationships between child and base entity are one-to-one on their pk columns, and all common fields are moved to the base table. 请注意,子实体与基本实体之间的关系在其pk列上是一对一的 ,并且所有公共字段都将移动到基表。 After creating your tables, right click on the models page in your visual studio, and select Update Model from Database... , and then in the add tab, select these 3 tables to add. 创建表格后,右键单击visual studio中的模型页面,然后选择“从数据库更新模型...” ,然后在“添加”选项卡中,选择要添加的这3个表。 At first you should see this model diagram, which needs to be changed a bit: 首先你应该看到这个模型图,需要稍微改变一下:
Do these steps for Person
and Organization
separately: 分别为Person
和Organization
执行以下步骤:
Identity
在Base Type属性中,选择Identity
Identity
选择然后删除此实体与Identity
之间的关联 After these steps save your model. 完成这些步骤后保存模型。 Now your model should look like this: 现在您的模型应如下所示:
Now compile your project and enjoy your life! 现在编译你的项目,享受你的生活!
Additional resources: 其他资源:
Entity Framework Designer TPH Inheritance 实体框架设计器TPH继承
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.