Mdb
Mdb

Reputation: 8556

configure many to many relationship in entity framework

So following this example:

http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

I have a Student class:

public class Student
    {
        public Student() { }

        public int StudentId { get; set; }

        public string StudentName { get; set; }

        public virtual ICollection<Course> Courses { get; set; }
    }

and a Course class

public class Course
    {
        public Course()
        {
            this.Students = new HashSet<Student>();
        }

        public int CourseId { get; set; }
        public string CourseName { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }

They have Many-to-Many relationship which is configured this way:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

       modelBuilder.Entity<Student>().HasMany<Course>(s => s.Courses).WithMany(c => c.Students).Map(c =>
        {
            c.MapLeftKey("Student_id");
            c.MapRightKey("Course_id");
            c.ToTable("StudentAndCourse");
        });

        base.OnModelCreating(modelBuilder);
    }

I have created the models and tables myself and map to them. So far so good. The problem is I do not need the collection of related Students to my courses. In other words when I get my courses they are coming with their related Students. I need the Students with the assigned Courses but when I get the courses through my repo, I need only them.

I tried to remove the Students collection from my Course class but was enable to fix the mapping. I am not experienced with EF and any help with working example will be greatly appreciated.

Upvotes: 0

Views: 94

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

There is WithMany() method which does not require navigation property for related entities:

 modelBuilder.Entity<Student>()
       .HasMany(s => s.Courses)
       .WithMany()
       .Map(c =>
    {
        c.MapLeftKey("Student_id");
        c.MapRightKey("Course_id");
        c.ToTable("StudentAndCourse");
    });

Upvotes: 2

Related Questions