Wednesday 1 April 2015

Self referencing association in entity framework with code first



Step1: Go to your application and Add a class (Student.cs) file to your application.

namespace Entity
{
    public class Student
    {
        public int StudentID { getset; }
        public string StudentName { getset; }
        public int? HODID { getset; }

        public Student HOD { getset; }
    }
}



Step 2: Add another class(StudentDBContext.cs)file to the project.
using System.Data.Entity;
namespace Entity
{
    public class StudentDBContext : DbContext
    {
        public DbSet<Student> Students { getset; }

        protected override void OnModelCreating(DbModelBuilder _model)
        {
           _model.Entity<Student>()
                .HasOptional(c => c.HOD)
                .WithMany()
                .HasForeignKey(c => c.HODID);

            base.OnModelCreating(_model);
        }
    }
}



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


Step 4: Add a webform to your application and Drag and drop a GridView control from tool box. 

Step 5: Write the below code.
using System;
using System.Linq;
namespace Demo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StudentDBContext studentDBContext = new StudentDBContext();
            GridView1.DataSource = studentDBContext.Students.Select(c => new
            {
                StudentName = c.StudentName,
                HODName = c.HOD == null ?
                    "Principle" : c.HOD.StudentName
            }).ToList();
            GridView1.DataBind();
        }
    }
}



Step 6: Run your application. Entity database and Students table will be created at this time. You see that StudentID is marked as primary key and HODID is marked as foreign key.

Step 7: Insert test data using the following SQL script

Insert into Students values ('Munesh', NULL)
Insert into Students values ('Rahul', NULL)
Insert into Students values ('Micale', NULL)
Insert into Students values ('Tom', NULL)
Insert into Students values ('Ram', NULL)
Insert into Students values ('Lick', NULL)
Insert into Students values ('ABC', NULL)
Go
Update Students Set HODID  = 5 Where StudentName IN ('Ram''Rahul')
Update Students Set HODID  = 3 Where StudentName IN ('Tom','Micale')
Update Students Set HODID  = 5 Where StudentName IN ('Lick')
Update Students Set HODID  = 4 Where StudentName IN ('ABC')
GO



Now Run your application you will see that respective name and others detail will see.

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