Entity Framework - Inheritance


Inheritance makes it possible to create complex models that better reflect how developers think and also reduce the work required to interact with those models. Inheritance used with entities serves the same purpose as inheritance used with classes, so developers already know the basics of how this feature works.

Let’s take a look at the following example and by creating a new console application project.

Step 1 − Add ADO.NET Entity Data Model by right-clicking on project name and select Add → New Item…

Step 2 − Add one entity and name it Person by following all the steps mentioned in the chapter Model First approach.

Step 3 − Add some scalar properties as shown in the following image.

Add Scalar Properties

Step 4 − We will add two more entities Student and Teacher, which will inherit the properties from Person Table.

Step 5 − Now add Student entity and select Person from the Base type combobox as shown in the following image.

Base Type ComboBox

Step 6 − Similarly add Teacher entity.

Step 7 − Now add EnrollmentDate scalar property to student entity and HireDate property to Teacher entity.

EnrollmentDate

Step 8 − Let's go ahead and generate the database.

Step 9 − Right click on the design surface and select Generate Database from Model…

Generate Database

Step 10 − To create new Database click on New Connection…The following dialog will open. Click OK.

New Database

Step 11 − Click Finish. This will add *.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file. Now right-click and select Execute.

Step 12 − Go to the server explorer you will see that the database is created with three tables which are specified.

Database Created Table

Step 13 − You can also see that the following domain classes are also generated automatically.

public partial class Person {
   public int ID { get; set; }
   public string FirstMidName { get; set; }
   public string LastName { get; set; }
}

public partial class Student : Person {
   public System.DateTime EnrollmentDate { get; set; }
}

public partial class Teacher : Person {
   public System.DateTime HireDate { get; set; }
}

Following is the Context class.

public partial class InheritanceModelContainer : DbContext {

   public InheritanceModelContainer() : 
      base("name = InheritanceModelContainer") {}

   protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      throw new UnintentionalCodeFirstException();
   }

   public virtual DbSet<Person> People { get; set; }
}

Let’s add some Students and Teachers to the database and then retrieve it from the database.

class Program {

   static void Main(string[] args) {

      using (var context = new InheritanceModelContainer()) {

         var student = new Student {
            FirstMidName = "Meredith", 
            LastName = "Alonso", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         };

         context.People.Add(student);

         var student1 = new Student {
            FirstMidName = "Arturo", 
            LastName = "Anand", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         };

         context.People.Add(student1);

         var techaer = new Teacher {
            FirstMidName = "Peggy", 
            LastName = "Justice", 
            HireDate = DateTime.Parse(DateTime.Today.ToString())
         };

         context.People.Add(techaer);

         var techaer1 = new Teacher {
            FirstMidName = "Yan", 
            LastName = "Li", 
            HireDate = DateTime.Parse(DateTime.Today.ToString())
         };

         context.People.Add(techaer1);
         context.SaveChanges();
      }
   }
}

Students and teachers are added in the database. NTo retrieve students and teacher, the OfType method needs to be used, which will return Student and Teacher related to the specified department.

Console.WriteLine("All students in database"); 
Console.WriteLine("");

foreach (var student in context.People.OfType<Student>()) {
   string name = student.FirstMidName + " " + student.LastName;
   Console.WriteLine("ID: {0}, Name: {1}, \tEnrollment Date {2} ", 
      student.ID, name, student.EnrollmentDate.ToString());
}

Console.WriteLine("");
Console.WriteLine("************************************************************ *****");
Console.WriteLine("");
Console.WriteLine("All teachers in database");
Console.WriteLine("");

foreach (var teacher in context.People.OfType<Teacher>()) {
   string name = teacher.FirstMidName + " " + teacher.LastName;
   Console.WriteLine("ID: {0}, Name: {1}, \tHireDate {2} ", 
      teacher.ID, name, teacher.HireDate.ToString()); 
}

Console.WriteLine("");
Console.WriteLine("************************************************************ *****");
Console.ReadKey();

In the first query, when you use OfType<Student>() then you will not be able to access HireDate because HireDate property is part of Teacher Entity and similarly EnrollmentDate property will not be accessible when you use OfType<Teacher>()

When the above code is executed, you will receive the following output −

All students in database
ID: 1, Name: Meredith Alonso,   Enrollment Date 10/30/2015 12:00:00 AM
ID: 2, Name: Arturo Anand,      Enrollment Date 10/30/2015 12:00:00 AM
*****************************************************************  
All teachers in database
ID: 3, Name: Peggy Justice,     HireDate 10/30/2015 12:00:00 AM
ID: 4, Name: Yan Li,    HireDate 10/30/2015 12:00:00 AM
*****************************************************************

We recommend that you execute the above example in a step-by-step manner for better understanding.

Advertisements