Entity Framework DB-First, implement inheritance

Ashkan picture Ashkan · Mar 8, 2014 · Viewed 11.3k times · Source

I'm trying to implement inheritance using entity framework 6.0 and database first approach. OK, let's say I have a Person and an Organization entity like below:

// 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:

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?

Answer

Ashkan picture Ashkan · Mar 8, 2014

One possible way is to use one table for each type called TPT (table-per-type), which I prefer to use. To achieve this, you define your tables like the model shown in the following picture:

table hierarchy

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. 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. At first you should see this model diagram, which needs to be changed a bit:

tables added at first

Do these steps for Person and Organization separately:

  • Right click on entity and select Properties
  • In the Base Type property select Identity
  • Select and then delete the association between this entity and Identity
  • Select and then Delete the PK (ID column) of this entity (Inherits from base entity)

After these steps save your model. Now your model should look like this:

the changed model

Now compile your project and enjoy your life!

Additional resources:
Entity Framework Designer TPH Inheritance