Table Per Hierarchy Inheritance in Entity Framework With Code First

This article explains Table Per Hierarchy (TPH) Inheritance in the Code First approach. First go through the article TPH With DataBase Approach.

Step 1

Go to your application and add a class (Student.cs) file to your application. Also make this class an Abstract class.

  1. namespace EntityInheritance {  
  2.     public abstract class Student {  
  3.         public int ID {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string FirstName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string LastName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Gender {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
Step 2

Add another class file to the project and name it CollageStudent.cs. Write the following code snippet:
  1. namespace EntityInheritance {  
  2.     public class CollageStudent: Student {  
  3.         public string StudentCollageName {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string StudentCollageBranch {  
  8.             get;  
  9.             set;  
  10.         }  
  11.     }  
  12. }  
Step 3

Add one more class file to the project from School student and name it SchoolStudent.cs.
  1. namespace EntityInheritance {  
  2.     public class SchoolStudent: Student {  
  3.         public string StudentSchoolName {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string StudentSchoolclass {  
  8.             get;  
  9.             set;  
  10.         }  
  11.     }  
  12. }  
Step 4

Add a class file for DBContext. Name it StudentDBContext.cs and write the following code:
  1. using System.Data.Entity;  
  2. namespace EntityInheritance {  
  3.     public class StudentDBContext: DbContext {  
  4.         public DbSet < Student > Students {  
  5.             get;  
  6.             set;  
  7.         }  
  8.     }  
  9. }  
Step 5

Add the database connection string in the web.config file.
  1. <connectionStrings>  
  2.    <add name="StudentDBContext"  
  3.    connectionString="server=.; database=EntityInheritance; integrated security=SSPI;"  
  4.    providerName="System.Data.SqlClient" />  
  5. </connectionStrings>  
Step 6

Add a Webform to the project and write the following code:
  1. <div style="font-family: Arial">  
  2.     <asp:Button ID=" Button1" runat="server" Text="All Student Information"  
  3. onclick="Button1_Click" />  
  4.     <asp:Button ID=" Button2" runat="server" Text="Collage Student Information"  
  5. onclick="Button2_Click" />  
  6.     <asp:Button ID=" Button3" runat="server" Text="School Student Information"  
  7. onclick="Button3_Click" />  
  8.     <asp:GridView ID="GridView1" runat="server"></asp:GridView>  
  9.     <asp:Button ID="btnAddcollageStudent" runat="server"  
  10. Text="Add Collage student" onclick=" btnAddcollageStudent _Click" />  
  11.     <br />  
  12.     <br />  
  13.     <asp:Button ID=" btnAddSchoolStudent " runat="server"  
  14. Text=" Add School Student " onclick=" btnAddSchoolStudent _Click" />  
  15. </div>  
Step 7

Copy the following code in the code-behind file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. namespace EntityInheritances {  
  6.     public partial class WebForm1: System.Web.UI.Page {  
  7.         protected void Button1_Click(object sender, EventArgs e) {  
  8.             GridView1.DataSource = ConvertListToDataTable(  
  9.             studentDBContext.Students.ToList());  
  10.             GridView1.DataBind();  
  11.         }  
  12.         protected void Button2_Click(object sender, EventArgs e) {  
  13.             GridView1.DataSource = studentDBContext.Students.OfType < CollageStudent > ().ToList();  
  14.             GridView1.DataBind();  
  15.         }  
  16.         protected void Button3_Click(object sender, EventArgs e) {  
  17.             GridView1.DataSource = studentDBContext.Students.OfType < SchoolStudent > ().ToList();  
  18.             GridView1.DataBind();  
  19.         }  
  20.         private DataTable ConvertListToDataTable(List < Student > students) {  
  21.             DataTable dt = new DataTable();  
  22.             dt.Columns.Add("ID");  
  23.             dt.Columns.Add("FirstName");  
  24.             dt.Columns.Add("LastName");  
  25.             dt.Columns.Add("Gender");  
  26.             dt.Columns.Add("SchoolStudentName");  
  27.             dt.Columns.Add("SchoolStudentClass");  
  28.             dt.Columns.Add("CollageStudentName");  
  29.             dt.Columns.Add("CollageStudentBranch");  
  30.             dt.Columns.Add("Type");  
  31.             foreach(Student _student in students) {  
  32.                 DataRow dr = dt.NewRow();  
  33.                 dr["ID"] = _student.ID;  
  34.                 dr["FirstName"] = _student.FirstName;  
  35.                 dr["LastName"] = _student.LastName;  
  36.                 dr["Gender"] = _student.Gender;  
  37.                 if (_student is CollageStudent) {  
  38.                     dr["CollageStudentName"] = ((CollageStudent) _student).CollageStudentName;  
  39.                     dr["CollageStudentBranch"] = ((CollageStudent) _student).CollageStudentBranch;  
  40.                     dr["Type"] = "CollageStudent";  
  41.                 } else {  
  42.                     dr["SchoolStudentName "] = ((SchoolStudent) _student).SchoolStudentName;  
  43.                     dr["SchoolStudentClass "] = ((SchoolStudent) _student).SchoolStudentBranch;  
  44.                     dr["Type"] = "SchoolStudent";  
  45.                 }  
  46.                 dt.Rows.Add(dr);  
  47.             }  
  48.             return dt;  
  49.         }  
  50.     }  
  51. }  
  52. protected void btnAddCollageStudent_Click(object sender, EventArgs e) {  
  53.     CollageStudent collagestudent = new CollageStudent {  
  54.         FirstName = " Munesh",  
  55.         LastName = "Sharma",  
  56.         Gender = "Male"  
  57.         CollageStudentName = "VIT"  
  58.         CollageStudentBranch = "IT"  
  59.     };  
  60.     StudentDBContext studentDB = new StudentDBContext();  
  61.     studentDB.Students.Add(collagestudent);  
  62.     studentDB.SaveChanges();  
  63. }  
  64. protected void btnAddSchoolStudent_Click(object sender, EventArgs e) {  
  65.     SchoolStudent schoolstudent = new SchoolStudent {  
  66.         FirstName = " Rahul",  
  67.         LastName = "Sharma",  
  68.         Gender = "Male"  
  69.         CollageStudentName = "KVM"  
  70.         CollageStudentBranch = "Seven"  
  71.     };  
  72.     StudentDBContext studentDB = new StudentDBContext();  
  73.     studentDB.Students.Add(schoolstudent);  
  74.     studentDB.SaveChanges();  
  75. }  
  76. }  
  77. }  
Step 8

First delete the “EntityInheritance” database in SQL Server if you have it.

Step 9

Now run the application. At this time your database and table will be created.

Step 10

Copy and paste the following query.
  1. Insert into Student values ('Munesh''Sharma','Male',null,null,'VIT','IT','CollageStudent')  
  2. Insert into Student values ('Rahul''Sharma','Male','KVM','Seven',null,null,'SchoolStudent')  
  3. Insert into Student values ('Sara''vilium','Female','Aadharsh','Eight',null,null,'SchoolStudent')  
  4. Insert into Student values ('Rani''hash','Female',null,null,'MIT','ECE','CollageStudent')  
  5. Insert into Student values ('XYZ''ABC','Female','Ravat','Tenth',null,null,'SchoolStudent')  
  6. Insert into Student values ('Anshuman''EFG','Male',null,null,'BTC','Mechenical','CollageStudent')  
Note: At this time the Discriminator column is created automatically based on the type of Student and the information is inserted.

You can visit this article in my blog

Up Next
    Ebook Download
    View all
    Pristine
    Read by 0 people
    Download Now!
    Learn
    View all