Wednesday, 15 April 2015

Many to many relationship in entity framework code first

Here we will learn Many-to-many relationship in entity framework code first.
In previous tutorial we took example on Student and StudentClasses and made many-to-many using DataBase first approach. We will continue this tutorial with this example.

Step 1: Add a another class file to the project, and give  Name it Classes.cs. write below code.
namespace EntityRelationShip
{
    public class Class
    {
        public string ClassID { getset; }
        public string  ClassName { getset; }
          public IList<Student> Students { get; set; }

    }
}

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

namespace EntityRelationShip
{
    public abstract class Student
    {
        public int ID { getset; }
        public string StudentName { getset; }
         public IList<Class> Class { get; set; }
    }
}

Step(3)  : Add a new class for giving DBContext and write below code. And give the name for this class is StudentDBContext.cs.
using System.Data.Entity;
namespace EntityRelationShip
{
    public class StudentDBContext : DbContext
    {
        public DbSet<Class> Courses { getset; }
        public DbSet<Student> Students { getset; }

        protected override void OnModelCreating(DbModelBuilder _model)
        {
           _model.Entity<Student>()
            .HasMany(t => t.Class)
            .WithMany(c => c.Students)
            .Map(C =>
            {
                c.ToTable("StudentClass");
                c.MapLeftKey("StudentID");
                c.MapRightKey("ClassID");
            });

            base.OnModelCreating(_model);
        }
    }
}


Step(4) : Add connection string to the Web.Config file
<connectionStrings>
  <add name="StudentDBContext"
        connectionString="server=.; database= EntityRelationShip; integrated security=SSPI;"
        providerName="System.Data.SqlClient" />
</connectionStrings>


Step 6: Right click on your application and add a webform to the project.
<div style="font-family: Arial">
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <br />    
</div>

Now write below code in Code-Behind file.
using System;
using System.Linq;

namespace EntityRelationShip
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StudentDBContext _student = new StudentDBContext();

            GridView1.DataSource = (from student in _student.Students
                                    from c in student.Classes
                                    select new
                                    {
                                        StudentName = student.StudentName,
                                        ClassName = c.ClassName
                                    }).ToList();

            GridView1.DataBind();
        }
}

Step 7: First delete “EntityRelationShip” 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 Classes values ('Seven')
Insert into Classes values ('Eight')
Insert into Classes values ('Nine')
Insert into Classes values ('Tenth')
GO

Insert into Students values ('Munesh')
Insert into Students values ('Rahul')

GO

Insert into StudentClasses values (1, 1)
Insert into StudentClasses values (1, 2)
Insert into StudentClasses values (2, 1)
Insert into StudentClasses values (2, 2)
Insert into StudentClasses values (2, 3)
GO



Now your Application and check your data in gridview.

Many-To-Many relationship in entity framework

Here we will learn many-to-many relationship in entity framework(EF) with database first approach.
Many to many relationship means suppose there is school registration site which contain multiple students and students can contain many classes. In general we can say that Many-to-Many relationship require a join b/w tables .
We will understand this with an example
(1)First copy below script and Write query and insert some values to these tables.
Create Table Classes
(
     ClassesID int identity primary key,
     ClassesName nvarchar(50)
)
GO

Create Table Students
(
     StudentID int identity primary key,
     StudentName nvarchar(50)
)
GO

Create Table StudentClasses
(
     StudentID int not null foreign key references Students(StudentID),
     ClassesID int not null foreign key references Classes(ClassesID)
     primary key (StudentID, ClassesID)
)
GO


Insert into Classes values ('Seven')
Insert into Classes values ('Eight')
Insert into Classes values ('Nine')
Insert into Classes values ('Tenth')
GO

Insert into Students values ('Munesh')
Insert into Students values ('Rahul')

GO

Insert into StudentClasses values (1, 1)
Insert into StudentClasses values (1, 2)
Insert into StudentClasses values (2, 1)
Insert into StudentClasses values (2, 2)
Insert into StudentClasses values (2, 3)
GO


(2)Go to your application and right click on solution explorer and add a ADO.Net Entity data Modal and select Database first approach if we generate entity then only 2 entity will generate for Student and classes with many-to-many relationship b/w them. Now if we  see entity navigation property to navigate from classes to Students and from Students to classes.

(3)At this point right click on Many-to-Many association and click on Table mapping in mapping screen s many-to-many association is mapped to StudentsClasses.

(4)Right click on you application and add a webform and drag and down a Gridview from toolbox and write below code at the Page_Load event of this web form.
StudentDBContext _studentDBContext = new StudentDBContext();

    GridView1.DataSource = from student in _studentDBContext.Students
                            from classes in student.Classes
                            select new
                            {
                                StudentName = student.StudentName,
                                ClassName = Classes.ClassName
                            };
    GridView1.DataBind();
}



Now Run your application you will see respective data in gridview. 

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

    }
       



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