Inheritance in Entity Framework Core

Inheritance is a key object-oriented programming concept that facilitates code reuse and is often used to model hierarchies. The following model represents various types of contracts that you might be able to enter into with a media/communications business:

public class Contract
{
    public int ContractId { get; set; }
    public DateTime StartDate { get; set; }
    public int Months { get; set;}
    public decimal Charge { get; set; }
}

public class MobileContract : Contract
{
    public string MobileNumber { get; set; }
}

public class TvContract : Contract
{
    public PackageType PackageType { get; set; }
}

public class BroadBandContract : Contract
{
    public int DownloadSpeed { get; set; }
}

public enum PackageType
{
    S, M, L, XL
}

The base type is Contract. Specific types of contract inherit from the base class: a mobile phone contract, a TV contract and a broadband contract. Each of the types of contract share the ContractId, StartDate, Duration and Charge properties with their base type through inheritance, and implement additional type-specific properties.

There are 3 ways in which object-oriented inheritance can be represented in a database:

Table Per Hierarchy (TPH)

One table is used to represent all classes in the hierarchy. A "discriminator" column is used to discriminate between differing types. The table takes the name of the base class or its associated DbSet property by default.

In previous versions of Entity Framework, TPH was the default mapping pattern for inheritance. Entity Framework Core currently only implements the TPH pattern.

Table Per Type (TPT)

A separate table is used to represent each type in the inheritance chain, including abstract types. Tables that represent derived types are related to their base type via foreign keys.

The TPT pattern is currently being considered for inclusion but no date has been decided yet.

Table Per Concrete Type (TPC)

A separate table is used to represent each concrete type in the inheritance chain. Properties in any abstract base type are generated as fields in each concrete type's table. There is no relationship between differing types. http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines

The TPC pattern is currently on the backlog, which means that it is being considered for inclusion as a feature, but no date has been set as yet.

Further Reading


Created:
Last updated: 28/03/2017 08:52:39
Proficiency Level: Intermediate