Building One To Many Relationship Using Entity Framework Code First

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.

Entity framework

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.

  1. public class Student  
  2. {  
  3.    public int StudentID { getset; }  
  4.    public string StudentName { getset; }  
  5.    public Grade Grade { getset; }  
  6. }  
After that add Grade class also.
  1. public class Grade  
  2. {  
  3.    public int GradeId { getset; }  
  4.    public string GradeName { getset; }  
  5.    public virtual List<Student> Students { getset; }  
  6. }  
We are using virtual property as a collection of student type.

Now add a Context class for database as below.
  1. public class StudentGradeDB : DbContext  
  2. {  
  3.    public DbSet<Grade> Grades { getset; }  
  4.    public DbSet<Student> Students { getset; }  
  5. }  
Now update your main() function with the following code.
  1. static void Main(string[] args)  
  2. {  
  3.     Console.WriteLine("Enter Student name = ");  
  4.     string stu_name = Console.ReadLine();  
  5.     try  
  6.     {  
  7.         using(vardb = newStudentGradeDB())  
  8.         {  
  9.             Student stu = newStudent();  
  10.             stu.StudentName = stu_name;  
  11.             db.Students.Add(stu);  
  12.             db.SaveChanges();  
  13.             Console.WriteLine(" Data Inserted...");  
  14.             Console.WriteLine("-----------( All Students )--------------");  
  15.             // Fetching data from Database  
  16.             var queryreslut = (from s indb.Students select s).ToList();  
  17.             // Display Data  
  18.             foreach(var item inqueryreslut)  
  19.             {  
  20.                 Console.WriteLine(item.StudentName);  
  21.             }  
  22.         }  
  23.     }  
  24.     catch (Exception ex)  
  25.     {  
  26.         Console.WriteLine("\n Error : \n" + ex.Message);  
  27.     }  
  28.     Console.ReadLine();  
  29. }  
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.
  1. <connectionStrings>  
  2.    <add name="StudentGradeDb"connectionString="Data Source=localhost;   
  3.    Initial Catalog=StudentGradeDb; user id=sa;password=12345;"  
  4.    providerName="System.Data.SqlClient" />  
  5. </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.

Result

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:

Table

 

Read more articles on Entity Framework: