There are several ways to map an inheritance relationship to a database table:
First: TPH (table-per-hiaerachy) one table per level (only one table)
Only a table with the name of a type named the parent class that contains all the property information for each subclass, using the Disciriminator column (usually the type name of the subclass), distinguishes which row represents what type of data.
Second: TPT (table-per-type) Each type has a table (the parent class and each subclass has a table)
The parent class, each child class, has a single table. There are only common data in the table of the parent class, and there are child class-specific attributes in the subclass table. TPT is much like the inheritance structure of a class. The parent table is associated with a child table by a foreign key.
The Third Kind: TPC (Table-per-concrete Class) specific subclass a table (subclass has a table)
Map non-abstract classes to the respective tables. The properties of each specific class, including the shared inheritance properties, are mapped to the respective database tables. The structure of its database is the same as it does not implement inheritance relationships.
TPC, TPH inheritance mode generally has better performance because TPT causes complex connection queries.
These three EF database mapping patterns can be implemented using the fluent API, by covering the Onmodelcreatin method in the DbContext class.
First, the realization of TPH.
In the entity Framework, the inheritance relationship defaults to using the TPH mode.
How to use:
1. Define the parent class first. Subclasses inherit the parent class and implement their own properties.
2. Add the parent class and subclass to the context. Such as
Public dbset<person> people {Get;set;}
Public dbset<instructor> instructors {Get;set;}
Public dbset<student> Students {get;set;}
In this way, there will only be one table for the person in the database, and a discriminator column is generated to differentiate whether the row represents student or instructor.
Second, the realization of TPT
Example:
Modelbuilder.entity<person> (). ToTable ("person");
Modelbuilder.entity<student> (). ToTable ("Student");
Modelbuilder.entity<instructor> (). ToTable ("instructor");
Third, the implementation of TPC
Example:
modelBuilder.Entity<Person>()
.Property(c => cID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Instructor>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Instructor");
});
modelBuilder.Entity<Student>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Student");
});
To implement an inheritance relationship in the Entity Framework mapping to a database table