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

放肆的年华 提交于 2019-12-01 03:39:40
Richard Deeming

According to this tutorial, you'll get the desired behaviour if your StudentCourse table only contains the foreign-key columns. If it contains any other columns, EF will generate an intermediate entity to represent the join.

In this case, dropping the surrogate key from the StudentCourse table and replacing it with a composite primary key should work.

markp3rry

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<Course> Courses { get; set; }

    public Student()
    {
        Courses = New HashSet<Course>();
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!