Entity Framework Many to Many relationships

Entity Framework

The more I use it, the more I love it! In fact, I’ve been developing with the .Net Framework and C# since version 1.1 and it just keeps getting better and better. I was a bit slow to adopt MVC and even slower to adopt Entity Framework, but now I have I can’t get enough of it. I know that sounds a bit sad, but I don’t care, it’s that good!

It’s not just the C# language or the frameworks that are good though, it also Visual Studio – which, in my opinion beats Xcode, Netbeans, Android Studio etc. hands down.

Many to Many

In this tutorial, I will be taking you through many-to-many relationships, and some example applications with MVC. It is worth pointing out that you don’t necessarily need to give any special consideration to many-to-many relationships as Entity Framework will handle it for you when it detects the need, but there are things you can do that we make it a bit neater and more controlled.

First I’m going to take you through how Entity Framework will handle them automatically. The scenario we are going to use is a simple user management system. The System will allow a Human Resources department to raise a request to have a new user set up. It will provide a section that will allow then to select equipment that the new user will need. The basic database structure will be as follows.

sql database diagram

Don’t worry about the departments table for now, but notice the “EquipmentToIssue” table and the “Users” table. The “EquipmentToIssue” table will contain things like desktop, or mobile phone, so we have a link table in between that and the User table in order to facilitate the many-to-many relationship.

Unadulterated Entity Framework

Let’s start by creating a new MVC project. So load up Visual Studio (I’m using 2013) and create a new ASP.Net Web application (I’m going to call mine UserTest but feel free with the name).

aspnetproject

Set the project type to MVC and change the authentication to whatever you like (I’d recommend no authentication for the purposes of this).

asp.net project type mvc

Next we need to get Entity Framework installed, so go to Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution. Entity Framework will probably be one of the first listed, but if not just type it in the search field.

nuget

then click on install. Right, now the action begins.

Code First

We are going to create our model using the “code first” approach. This is always my preferred method, mainly due to the migrations functionality (we’ll get into that a llittle a bit later).

more to follow….

Leave a Reply

Your email address will not be published. Required fields are marked *