简体   繁体   中英

Many to Many Relation with Lookup table Entity Framework

I am trying to create many to many relation with a Lookup table. Suppose i have a table "Course" that has 3 possible courses :

Course
Id | Name
1  | History
2  | Maths
3  | Science

I have another table Students where I will create Students such as :

Student
Id | Name

I have a mapping table which is StudentCourse:

StudentCourse
ID | StudentId | CourseId
1  |   1       | 3

Here is my Student & Course class:

public class Student : Entity<Student,int>
{
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course : Entity<Course,int>
{
    public virtual ICollection<Student> Student { get; set; }
}

Finally, here is the configuration code:

   modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });

When i create Student entity from view , the user selects the course from Course table and sends it to entity framework and EF should make entry to only Student and StudentCourse table .

But in my scenario, the course table is getting new entries for the selected courses. So I end up with duplicates in course table.

How do I tell entity framework to not make entry in Course table as it already has all the possible courses ... Please help !!

the issue was that I was populating my object in presentation layer and hence dbcontext under unit of work did not know about the nested objects.That is why it will always try to re create the Course even if it already exists. To fix this, populate Course object under same unit of work dbcontext.

ex:

  student.Course = UnitOfWork.Repository.FindById(id);
  var model = UnitOfWork.Repository.Add(student);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM