Creating N to N Relationships in MVC

This page is to help create, manage, and display n:n relationships – here are some steps (there are many ways to do this).

The end goal of this tutorial will be to create a Grade sheet that shows many to many relationship between grades and students like this 

Step 1. In my project I am going to do this the fastest way by simply creating an Entity Data Model in one  step. I already have an existing project and I select Add New Item by right clicking on the Models folder.

I am going to create an Empty Entity Framework Model and fill it in from the database

This will allow you to view the model – of course we do not have one yet – I am going to Read a Model from the Database in MVC.

Once you have uploaded a model from the database you will see it in your model browser.

And here is your code – should look familiar with what you would expect in an n:n relationship 

class Class

namespace SampleNtoN.Models

{

    using System;

    using System.Collections.Generic;

 

    public partial class Class

    {

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

        public Class()

        {

            this.Grades = new HashSet<Grade>();

        }

 

        public int ClassId { get; set; }

        public string ClassName { get; set; }

 

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Grade> Grades { get; set; }

    }

}

class Student

namespace SampleNtoN.Models

{

    using System;

    using System.Collections.Generic;

 

    public partial class Student

    {

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

        public Student()

        {

            this.Grades = new HashSet<Grade>();

        }

 

        public int StudentId { get; set; }

        public string StudentName { get; set; }

 

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Grade> Grades { get; set; }

    }

}

class Grades

namespace SampleNtoN.Models

{

    using System;

    using System.Collections.Generic;

 

    public partial class Grade

    {

        public int GradeId { get; set; }

        public int StudentId { get; set; }

        public int ClassId { get; set; }

        public string Grade1 { get; set; }

 

        public virtual Class Class { get; set; }

        public virtual Student Student { get; set; }

    }

}

Next: Creating and Displaying N to N Relationships part 2