首页 > 代码库 > Entity Framework 继承
Entity Framework 继承
1. Table per Hierarchy
基类和继承类存储在同一张数据表中,通过一个专门的字段(Identifier Column)进行区分。
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Employee>() .Map<FullTimeEmployee>(m => m.Requires("EmployeeType").HasValue(1)) .Map<HourlyEmployee>(m => m.Requires("EmployeeType").HasValue(2)); }
The best practice is that if your application never needs instances of the base entity is to make it abstract.
2. Table per Type
通过一个 "One to One" 的关联表来分别存储基类和继承类字段 (继承表的 ID 主键不要设成自增类型)
Table per type inheritance provides a lot of database flexibility because we can easily add tables as new derived types find their way into our model as an application develops. However, each derived type involves additional joins that can reduce performance. In real-world applications, we have seen significant performance problems with TPT when many derived types are modeled.
3. Table per concrete Class
"Table per concrete Class, TPC" 也是多表继承模式,和 "Table per Type" 的区别在于继承表包含基表的全部字段。这种方式不常用,且需要手工编辑映射关系。