Wednesday, 15 April 2015

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. 

No comments:

Post a Comment

Paging in html table using javascript

I demonstrated how to use HTML tables on the client for a very simple client-side paging solution. I have heard from several people who p...