Thursday 9 April 2015

Inheritance in entity framework

In previous tutorials we creates database tables which are based on domain classes. we can design our domain classes using inheritance in EntityFramework. Oops techniques includes "has a" and "is a" relationship whereas SQL based relational has only a "has a" relationships between database tables. SQL database management don't support type inheritance. So Here we will learn How to map with domain class.
There are three different approaches to get an inheritance hierarchy:
Table per Hierarchy (TPH): Inheritance is nothing but it is a hierarchical concept, means where one class is derived from another class. In TPH inheritance one database table stores Full data for all the entities in the inheritance hierarchy Format.
 Table per Type (TPT): This Creates separate table for each domain class or POCO class.
Table per Concrete class (TPC): This create one table for one concrete class, but not for the abstract class. So when you inherit the abstract class in multiple concrete classes then the properties of the abstract class will be part of each table of concrete class.
We Will understand per Hierarchy (TPH) With an example.
Step(1): Go to SqlServer management studio nad execute the following query.
Create Table Student
(
     ID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50),
     StudentSchoolName nvarchar(50),
     SchoolStudentclass nvarchar(50),
     StudentCollageName nvarchar(50),
     CollageStudentBranch nvarchar(50)
     Discriminator nvarchar(50)
)


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')




Step(2): Right click on your application and add a new item as “Ado.net entity Data Modal” after click Ok select database first approach.
Give your connection and select “Student” table here you will see only one entity but we want 3 entity entity.

Step(3): Here in this entity Student common information (like . ID,Firstname,Lasrname,Gender) will be abstract class.
And other entity like “Address, mobile” and collage ,branch will inherit this abstract class.
Step(4): To achieve this using EF designer.
(1)  Right click on designer surface and select Add New -> Entity
(2)  At this screen you give your new entity name “Student Address info” and Base type will be you abstract entity  then you cut Address and mobile from Base entity and paste it in new entity, After that your entity will be look like that.


(3)  Again right click on designer surface and do same process for adding new entity and give it name as “ Student Study info”. And paste Collage and branch to this entity.



(4)  At this point you have 3 entity and these 2 new entity will be inherited from Base Student  entity.


(5)  Right click on SchoolStudent and click on table Mapping and there map Schoolstudent Entity to Student Table, And also Give the conditional mapping in which we are using Discriminator  column to determine that it is School student or Collage Student.


(6)  Again same gose to Collagestudent entity  menas map this entity with Student table and give Discriminator  condition.

(7)  Now when we will compile this application it will give error because we are using Discriminator  column both side so delete Discriminator column from Student entity.
(8)  Now finally right click on Student entity and click on properties and Set “Abstract=true. This will make Student  class an abstract class. 
<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>
</div>


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;
        }
    }
}



(9)  Now Run your application and  Check your data.

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...