Reputation: 8556
So following this example:
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
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