Can Entity Framework handle many to many relationship without an intersection object?

后端 未结 2 386
有刺的猬
有刺的猬 2021-01-11 23:30

Using database first model: Let\'s say we have the classic tables Student, Course and StudentCourse (the latter obviously having FKs t

2条回答
  •  死守一世寂寞
    2021-01-11 23:47

    You can do it in EF Code First using ICollections. For example:

    public class Student 
    { 
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual ICollection Courses { get; set; }
    
        public Student()
        {
            Courses = New HashSet();
        }
    }
    

    Repeat for Course and swap it all over. This will create three tables in your database (Student, Course and StudentCourse) with a m-to-m relationship. Most importantly StudentCourse will be an invisible linking table that has no Entity in your model.

提交回复
热议问题