Wednesday 15 April 2015

Entity Relationships in Entity framework

A relationship in Entity framework is that there is a situation that exists between two database tables in which one table has a foreign key and the foreign key has reference the primary key(PK)
Of  the another table, A relationship allow relationship database to split and store data in different tables. for example if we want to store student private information and student education information then we need two tables.
One table for student private information and another table for student education information.
In Entity framework there are 3 type of relationship
  • One-to-One Relationships
  • One-to-many/Many to One Relationships
  • Many-to-Many Relationships

One-to-One Relationships :
Here we will understand one to one Entity relationship b/w student and StudentCollageInfo. As One-to- one relationship happens when primary key of one table become PK and FK of another table.
                In our example StudentID is the PK(primary key) of student table and StudentID will be Foreign key (FK) in StudentCollageInfo table for the relationship b/w the tables.
Notice that in SqlServer One To One relationship technically not possible it always One to Zero or Zero.
Firstly we will understand this with Code first approach for this we have to declare property.
 
    public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public virtual StudentCollageInfo _studentCollageInfo { get; set; }

    }
    
    public class StudentCollageInfo
    {
        [Key, ForeignKey("Student")] // This is dataAnoation we are using here 

        public int StudentId { get; set; }
       
        public string CollageName { get; set; }
        public string StudentBranch { get; set; }       

        public virtual Student Student { get; set; }
    }

 One-to-Zero-or-One entity relationship using Fluent API:
The below example for one-to-zero or one relationship between Student and StudentAddress using Fluent API.
  
    Public  void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Configure StudentId as PK for StudentAddress
        modelBuilder.Entity<StudentCollageInfo>()
            .HasKey(e => e.StudentId);
       
        // StudentId as FK for StudentCollageInfo
        modelBuilder.Entity<Student>()
                    .HasOptional(s => s._studentCollageInfo) // Mark StudentCollageInfo is optional for Student
                    .WithRequired(ad => ad.Student); // it will Create inverse relationship

    }
       
In above example, we set primary key(PK) to StudentId for Studentcollageinfo because it doen't follow Code First conventions for primary(PK). Then in second line, HasOptional method make StudentCollageInfo property nullable then WithRequired method will create inverse relationship by making StudentId column as forgion key in StudentcollageInfo table. Thus, StudentId will be PK and FK in StudentAddress which makes one-to-zero or one relationship.
Alternatively, we can also configure Studentcollageinfo entity as shown below.
  
    Public  void OnModelCreating(DbModelBuilder _builder)
    {
        // Configure StudentId as priamry for Studentcollageinfo
        _builder.Entity<StudentCollageInfo>()
            .HasKey(e => e.StudentId);
       
        // Configure StudentId as FK for Studentcollageinfo
        _builder.Entity<StudentCollageInfo>()
                    .HasRequired(c => c.Student)
                    .WithOptional(c => c._studentCollageInfo);

    }
       



Monday 13 April 2015

Table Per Type inheritance in entity framework code first

Here we will learn TPT(Table Per Type) Inheritance in Code first approach Before this learn this TPT 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 StudentCollageName { getset; }
        public string  StudentCollageBranch { getset; }

    }
}

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 StudentSchoolName { getset; }
        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 (1, 'Munesh''Sharma','Male')
Insert into Student values (2, 'Rahul''Sharma','Male')
Insert into Student values (3, 'Sara''vilium','Female')
Insert into Student values (4, 'Rani''hash','Female')
Insert into Student values (5, 'XYZ''ABC','Female')
Insert into Student values (6, 'Anshuman''EFG','Male')


Insert into CollageStudents values (1, 'VIT','IT')
Insert into CollageStudents values (4, 'MIT','ECE')
Insert into CollageStudents values (6, 'BTC','Mechenical')



Insert into SchoolStudents values (2, 'KVM','Seven')
Insert into SchoolStudents values (3,'Aadharsh','Eight')
Insert into SchoolStudents values (5, 'Ravat','Tenth')
s


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