问题
Using database first model: Let's say we have the classic tables Student
, Course
and StudentCourse
(the latter obviously having FKs to Student
and Course
).
If you import this model to EF, you will get an object generated for each of them. The Student
and Course
classes will each have a collection of StudentCourses
, from which you need to jump another relationship to get to the Course
or Student
, respectively.
I would like to have the code generated in such a way that the underlying intersection table is invisible, i.e. Student
has a collection of Courses
, and Course
has a collection of Students
. I have seen this done in other ORM software (specifically, TopLink). Can it be done in EF?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/13588574/can-entity-framework-handle-many-to-many-relationship-without-an-intersection-ob