When you work on relational databases, you find many scenarios where you need to use “one to many relationships” or “Many to many relationships” or “one to one relationships” into your model. Though entity framework is the most recommended choice by experienced programmers, while working on your project when you choose code first approach, it’s very easy to build relationships in code classes. So let’s get started.
Installation and Configuration of Entity framework
If you don’t know how to install entity framework see my previous article Entity framework from Scratch, where I wrote about Installation of Entity framework and how to perform simple CRUD operation using Entity framework Code First Approach.
Make a new project in visual studio with the name “One to Many relationship in EF”. Entity framework supports the following types of relationships. We shall discuss one to many relationship here.
- One to many relationship
- Many to many relationship
- One to one relationship
Workflow and Example
Let’s take a simple example of Student and Class. Let’s assume for a moment that one student belongs to one class at a time, but one class has more than one student at the same time. So this is a simple example of a one to many relationship.
[Note: we are using a simple console application to let you understand the things on very beginner level and easily.]
So these are the steps you need to follow in order to learn the “building one to many relationship” using entity framework code first.
- Make a simple console application.
- Add two classes with the name “Student” and “Grade”.
Making a relationship between both class (we’ll use navigation properties)
- Add a Context class with name “StudentGradeDb”.
- Add a connection string to force entity framework to create the database into our local SQL Server (otherwise we would not be able to see the one to many relationship clearly).
- Write code to take input for both tables from user into main() function and show the data of both to the user.
- Build and Run the project.
- Open SQL Server and analyze the database.
Let’s Add a Student class to program.
- public class Student
- {
- public int StudentID { get; set; }
- public string StudentName { get; set; }
- public Grade Grade { get; set; }
- }
After that add Grade class also.
- public class Grade
- {
- public int GradeId { get; set; }
- public string GradeName { get; set; }
- public virtual List<Student> Students { get; set; }
- }
We are using virtual property as a collection of student type.
Now add a
Context class for database as below.
- public class StudentGradeDB : DbContext
- {
- public DbSet<Grade> Grades { get; set; }
- public DbSet<Student> Students { get; set; }
- }
Now update your main() function with the following code.
- static void Main(string[] args)
- {
- Console.WriteLine("Enter Student name = ");
- string stu_name = Console.ReadLine();
- try
- {
- using(vardb = newStudentGradeDB())
- {
- Student stu = newStudent();
- stu.StudentName = stu_name;
- db.Students.Add(stu);
- db.SaveChanges();
- Console.WriteLine(" Data Inserted...");
- Console.WriteLine("-----------( All Students )--------------");
-
- var queryreslut = (from s indb.Students select s).ToList();
-
- foreach(var item inqueryreslut)
- {
- Console.WriteLine(item.StudentName);
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("\n Error : \n" + ex.Message);
- }
- Console.ReadLine();
- }
Before running this program we need to change the connection string. Add this connection string under the
config Sections under configurations tag in
App.config file. I’ve already written the procedure ofhow you can change the connection string here
Change connection string to SQL Server (localhost) in Entity framework.
- <connectionStrings>
- <add name="StudentGradeDb"connectionString="Data Source=localhost;
- Initial Catalog=StudentGradeDb; user id=sa;password=12345;"
- providerName="System.Data.SqlClient" />
- </connectionStrings>
Build your project and run it. The program will ask for input. Provide some name forthe student then it will take some time to load the data because in background it is creating database for us.
After that if you open your SQL Server, you will see the database has been created there with two tables and both tables has one to many relationship over there.
Create a database diagram of both tables, you’ll notice that relations is already existing between both tables as I’ve shown in the following screenshot:
Read more articles on Entity Framework: