Search code examples
asp.net-mvcmodelmappingmany-to-many

Mapping Many to many relationship with single model


My model

public class Student
    {
        public int id{ get; set; }

        public string Name{ get; set; }

        public string Qualification{ get; set; }

   }

In my project i am trying to create partners of student where a student can be partner with any number of student. i know i can achieve that by creating another model like this

 public class Partners
    {

        public string student1ID{ get; set; }

        public string student2ID{ get; set; }

   }

And insert values but just want to know if is there any other way to achieve this using virtual list<> etc.


Solution

  • To make a relation like each student will have one or more partners you can do this:

    public class Student
    {
        public int Id{ get; set; }
        public string Name{ get; set; }
        public string Qualification{ get; set; }
        public virtual ICollection<Partner> Partners{ get; set; }     
    }
    
    public class Partner
    {
        public int Id{ get; set; }
        public virtual Student Student{ get; set; }
    }