views:

62

answers:

1

I'm trying to get a one to many relationship mapped with the EF and for some reason it's proving more difficult than usual. This is my EDMX and DB Schema. The reason I used an auto-increment key on the middle table is because I was told it's difficult to use composite keys with the EF.

What I need is to be able to do (with a Course entity) someCourse.Students or (with a student entity) someStudent.Courses. Could anyone give me some pointers as to the best way of mapping this?

alt text alt text

+3  A: 

If you remove the AssociationID column and make both the StudentID and CourseID the primary key of the StudentCourses table, it will pick up the many-to-many relationship and generate more intuitive entity classes (ie Student.Courses, Course.Students)

Veli
Thanks, works perfectly.One problem though, I'm having problems deleting a student from a course or vice versa. I can get the data out of the entity no problem, but when I come to save changes nothing is persisted. Eg: var requestedCourse = context.Courses.Where(c => c.CourseID == CourseId).FirstOrDefault();System.Diagnostics.Debug.WriteLine(student.Courses.Count); // 0 student.Courses.Remove(requestedCourse);System.Diagnostics.Debug.WriteLine(student.Courses.Count); // still 0
Echilon
Turns out an Include("Courses") was needed to allow the course to be deleted.
Echilon