Relationships In Entity Framework Core

Relationships in EF Core

While working with Relational Database there comes a need to relate the two entities as per the requirement needed. When we try to establish a relation between two entities then one of them acts as a Principal entity and another acts as a Dependent entity.

Let's first look at these two terms and then will move forward:

  • Principal Entity: This is an Entity that contains Primary key properties into it.
  • Dependent Entity: This is an Entity that contains Foreign key properties into it.

Relationships Between entities are established using the foreign keys. which allows queries to be made on the database to obtain meaningful results.

Before Moving to relationships let's first understand a few more terminologies that are being used to establish the relationship:

  • Primary Key: Primary key is a column in the Table that Uniquely identifies each row in the table.
  • Foreign Key: Foreign key binds the two columns by mapping the primary key of the principal Entity.
  • Navigation Properties: Navigation properties define the type of relationships amongst the Entity. Based on the requirements, these properties are defined either in principle entity or in Dependent Entity.

There are two types of Navigation Properties:

  • Reference Navigation Property: Property that contains a reference to a single related entity (Zero to One Or One to One).  
  • Collection Navigation Property: Property that holds the reference to many related entities (One to Many Or Many to Many).

Types of Relationships

Tables can have a variety of relationships. Specifically, there are three types of relationships that we are going to see further in this article.

  1. One to One
  2. One to Many
  3. Many to Many

One to One relationship

A One-to-One relationship occurs when there is only one row in one table that is linked to only one row in another table and the other way around.

For a better understanding, let's take an example.

Consider the Class Student and StudentAddress. Let's Assume that Every Student has Only one Address, so this will Create One to One relation between Student and StudentAddress. Where StudentId from Student Table will act as a Primary key and StudentAddressId from StudentAddress table will act as a Primary as well as Foreign key which references the Primary key of the Student table.

Here's what our model will look like:

Student.cs Model

namespace EFCoreRelationships.Models
{
    class Student
    {
        public int StudentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        //Navigation Property
        public virtual StudentAddress StudentAddress { get; set; }
    }
}

StudentAddress Model

namespace EFCoreRelationships.Models
{
    class StudentAddress
    {
        [Key,ForeignKey("Student")]
        public int StudentAddressId { get; set; }
        public string StreetAddress { get; set; }
        //Navigation Property
        public virtual Student Student { get; set; }

    }
}

Note: Here Properties are defined as Virtual so that the Entity Framework can allow using lazy loading and efficient change tracking.

As we can see that we have added reference navigational property of other entity that references to the entity where the navigational property is defined. In Our Example Student class contains reference to StudentAddress Navigation Property and StudentAddress class Contains reference of Student Class.

Just add the migrations and update the database to reflect the One-to-One relationships between the entities.

One to Many relationship

The one-to-many relationship is formed when a row from first table is linked with many row in second table, but only one row from second table is linked with one row from first table.

Let’s Understand this with an Example,

Again now Considering Student and StudentCourse. So, let's assume that Each Course can have as many Students but Each Student has only one StudentCourse.

Thus relationship between Student and the StudentCourse is one to many. The Student belongs to only one StudentCourse. The StudentCourse can have many Students. In a One to Many relationship Primary key of the StudentCourse table (StudentCourseID) is defined as Foreignkey in the Student’s table.

For One to Many relationship here's what our model will look like:

Student.cs Model

namespace EFCoreRelationships.Models
{
    class Student
    {
        public int StudentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        //Navigation Property
        public virtual StudentCourse StudentCourse { get; set; }
    }
}

StudentCourse.cs Model

namespace EFCoreRelationships.Models
{
    class StudentCourse
    {
        public int StudentCourseId { get; set; }
        public string CourseName { get; set; }
        //Collection Navigation Reference
        public virtual ICollection<Student> Students { get; set; }
    }
}

As we can see that navigational property in the Student class returns the reference of the StudentCourse Class. And the navigational property in StudentCourse class returns the Student’s collection. EF Core will configure the classes that depend on each other here.

Again Add the Migrations and Update the Database to see the reflection on SQL Server.

Many to Many relationship

A Many to Many relationship occurs when multiple rows from one table are linked with multiple rows from another table and vice versa.

Let’s continue with the same example.

As Student and StudentTeacher are termed as Many to Many Relationship. The Student has more than one teacher for teaching various subjects. And Teacher can have many Students. Such relationships often involve creating a join table. A composite primary key will be constructed for the join table by combining the primary keys of the Student table and the StudentTeacher table.

For Many to Many relationship here's what our model will look like,

Student.cs Model

namespace EFCoreRelationships.Models
{
    class Student
    {
        public int StudentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        //Collection Navigation Reference
        public virtual ICollection<StudentTeacher> StudentTeacher { get; set; }
    }
}

StudentTeacher.cs Model

namespace EFCoreRelationships.Models
{
    class StudentTeacher
    {
        public int StudentTeacherId { get; set; }
        public string TeacherName { get; set; }
        //Collection Navigation Reference
        public virtual ICollection<Student> Students { get; set; }
    }
}

As Here in the Model Collection Reference Navigation Property is used which returns the Collection set of StudentTeacher and Student and Creates a Join Table which Contains Primary Key of Both the Tables and acts as Primary and Foreign key for that joint Table

Let's look at that by creating another Migration and Updating Database.

As we can see that StudentStudentTeacher is a Joint table Containing both StudentTeacherId and StudentStudentId as a Primary and Foreign Key through which we can Query the tables based on our needs.

Conclusion

In this article, we have seen how to establish One to One, One to Many, and Many to Many relationships among entities using the EF Core Code First approach and also implemented that with the help of example.