At the end of unfortunate 2020, the stable version of Entity Framework Core 5.0 was released. One of the features that appeared there was the improvement of the many-to-many relationship mechanism. In today’s post, I would like to introduce you to what this change is all about.
If you do not know what Entity Framework is (which is rather unlikely) then it is a database access tool. It can be described as an object relation mapper (ORM) we use to map our data in a relational database into objects of our applications.
Before moving on to describing and showing the changes that have taken place in the Entity Framework, I will explain briefly what the many-to-many relationship is.
Let’s imagine a situation that you have to create software for managing a university. The task of the system will, among other things, control the registration of students for various classes. So we have a situation where many students can register for many classes. On the other hand, classes can have many students. This is a typical example of a many-to-many relationship. So we have two tables that have a relationship with each other:
How is such a relationship approached in database design?
The way to do this in a relational database is by creating a table in the middle that we call the association table or the join table. Each row in this table is going to link up one student to one class as you can see below:
So let’s start by creating the classes that correspond to the database tables mentioned earlier. We have got a student with an id, name and student number, then a class with an id, name and description. Finally, a registration that represents the association I have described before.
Now we have some data to show what change has been made in the latest version of EF. We have students, two classes and several registrations there. After storing this on the database, we want to get a list of all students enrolled in math.
So how do you do it in a nicer way, with less code, using EF Core 5.0?
As I mentioned earlier, Registration is just a detail about how the many-to-many is implemented in a database. However, in our backend C# code, we do not want to care about it. So what can we do about it? Well, we can implement our models as follows without the middle table:
At this moment, we have navigations from the class directly to the students and the same in the other direction. We can now go back to our data and make the appropriate changes there. We no longer have registrations, but see the students in their classes. Thanks to this, we get rid of unnecessary code. We need to make a small change to our query as well. Finally, the code looks like this:
It is nice that this change has finally been implemented in EF 5.0 Core. Thanks to that it is much easier to operate on tables that have many-to-many relationships. There is nothing better for a programmer than to get rid of unnecessary code while maintaining previous functionality, right?