Saturday 11 April 2015

Table Per Hierarchy inheritance in entity framework with code first

Here we will learn TPH(Table Per Hierarchy) Inheritance in Code first approach Before this learn this TPH With DataBase Approach.
Step1: Go to your application and Add a class (Student.cs) file to your application. And make this class as Abstract class.
namespace EntityInheritance
{
    public abstract class Student
    {
        public int ID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Gender { getset; }
    }
}


Step 2: Add a another class file to the project, and give  Name it CollageStudent.cs. write below code.
namespace EntityInheritance
{
    public class CollageStudentStudent
    {
        public string StudentCollageNamegetset; }
        public string  StudentCollageBranchgetset; }

    }
}


Step 4: Add a one more class file to the project from School student. Name it SchoolStudent.cs.
namespace EntityInheritance
{
    public class SchoolStudent : Student
    {
        public string StudentSchoolNamegetset; }
        public string  StudentSchoolclass getset; }
    }
}



Step 5: Add a class file for DBContext. Name it StudentDBContext.cs. And write below code.
using System.Data.Entity;
namespace EntityInheritance
{
    public class StudentDBContext : DbContext
    {
        public DbSet<Student> Students { getset; }
    }
}


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


Step 7: Add a webform to the project.Write below code
<div style="font-family: Arial">
       <asp:Button ID=" Button1" runat="server" Text="All Student Information"
        onclick="Button1_Click" />
   <asp:Button ID=" Button2" runat="server" Text="Collage Student Information"
        onclick="Button2_Click" />

   <asp:Button ID=" Button3" runat="server" Text="School Student Information"
        onclick="Button3_Click" />

    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

<asp:Button ID="btnAddcollageStudent" runat="server"
        Text="Add Collage student" onclick=" btnAddcollageStudent _Click" />
    <br />
    <br />
    <asp:Button ID=" btnAddSchoolStudent " runat="server"
        Text=" Add School Student " onclick=" btnAddSchoolStudent _Click" />

</div>

Step 8: Copy the following code in the code-behind file.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace EntityInheritances
{
    public partial class WebForm1 : System.Web.UI.Page
    {
protected void Button1_Click(object sender, EventArgs e)
    {
 GridView1.DataSource = ConvertListToDataTable(
                        studentDBContext.Students.ToList());
                    GridView1.DataBind();


}
protected void Button2_Click(object sender, EventArgs e)
    {
 GridView1.DataSource = studentDBContext.Students
                        .OfType<CollageStudent>().ToList();
                    GridView1.DataBind();


}
protected void Button3_Click(object sender, EventArgs e)
    {
  GridView1.DataSource = studentDBContext.Students
                        .OfType<SchoolStudent>().ToList();
                    GridView1.DataBind();


}

private DataTable ConvertListToDataTable (List<Student> students)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            dt.Columns.Add("Gender");
            dt.Columns.Add("SchoolStudentName");
            dt.Columns.Add("SchoolStudentClass");
            dt.Columns.Add("CollageStudentName");
            dt.Columns.Add("CollageStudentBranch");
            dt.Columns.Add("Type");

            foreach (Student _student in students)
            {
                DataRow dr = dt.NewRow();
                dr["ID"] = _student.ID;
                dr["FirstName"] = _student.FirstName;
                dr["LastName"] = _student.LastName;
                dr["Gender"] = _student.Gender;

                if (_student is CollageStudent)
                {                
     dr["CollageStudentName"] = ((CollageStudent) _student). CollageStudentName;
   dr["CollageStudentBranch"] = ((CollageStudent) _student).CollageStudentBranch;

                   
                    dr["Type"] = "CollageStudent";
                }
                else
                {
                   dr["SchoolStudentName "] = ((SchoolStudent) _student).SchoolStudentName;
dr["SchoolStudentClass   "] = ((SchoolStudent) _student).SchoolStudentBranch;
                    dr["Type"] = "SchoolStudent";
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }
}
        protected void btnAddCollageStudent_Click(object sender, EventArgs e)
        {
            CollageStudent collagestudent = new CollageStudent 
            {
                FirstName = " Munesh",
                LastName = "Sharma",
                Gender = "Male"  
               CollageStudentName = "VIT"  
              CollageStudentBranch= "IT"  
            };
                    
            StudentDBContext studentDB = new StudentDBContext ();
           studentDB.Students.Add(collagestudent);
           studentDB.SaveChanges();
        }

        protected void btnAddSchoolStudent_Click(object sender, EventArgs e)
        {
            SchoolStudent schoolstudent = new SchoolStudent 
            {
                FirstName = " Rahul",
                LastName = "Sharma",
                Gender = "Male"  
               CollageStudentName = "KVM"  
              CollageStudentBranch= "Seven"  
            };
                    
            StudentDBContext studentDB = new StudentDBContext ();
           studentDB.Students.Add(schoolstudent);
           studentDB.SaveChanges();
        }
    }


}





Step 7: First delete “EntityInheritance” Database in SqlServer if you have it.

Step 8: Now Run the application. At this time your database and your table will be created.
Step 9: Copy and pest below query.
Insert into Student values ('Munesh''Sharma','Male',null,null,'VIT','IT','CollageStudent')
Insert into Student values ('Rahul''Sharma','Male','KVM','Seven',null,null,'SchoolStudent')
Insert into Student values ('Sara''vilium','Female','Aadharsh','Eight',null,null,'SchoolStudent')
Insert into Student values ('Rani''hash','Female',null,null,'MIT','ECE','CollageStudent')
Insert into Student values ('XYZ''ABC','Female','Ravat','Tenth',null,null,'SchoolStudent')
Insert into Student values ('Anshuman''EFG','Male',null,null,'BTC','Mechenical','CollageStudent')



Note :-  At this time Discriminator column is created automatically based on the type of Student  information is  inserted. 

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...