Entity Framework retrieve objects based in condition

c# dbcontext entity-framework-6

Question

I am developing an Web Api application using Entity Framework where I have these two models and my DbContext class:

public class Course
{
    [Key]
    public int CourseId { get; set; } 

    [Required]
    public string CourseName{ get; set; }

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

}

public class Students
{
    [Key]
    public int StudentId { get; set; } 

    [Required]
    public string StudentName{ get; set; }

    [Required]
    public int StudentAge{ get; set; }

}

//My CourseContext
public class CourseContext : DbContext
{
    public CourseContext () : base("CourseDB") { }

    public DbSet<Course> Courses { get; set; }

    public DbSet<Students> Students { get; set; }
}

I am modeling a WebAPi with these models above and I need to list all students that are taking a course which means that are added to the ICollection Students property in Course Class. I have tried to develop a solution for that but I have no idea how to do that since I do not have a foreign key property between the models.

...
using (var course_db = new CourseContext ()){


/*but this return all students and repeated ones since one student 
can be in more than one course*/

var students= course_db.Course.Include("Students").Select(x=> x.Students);

if (students== null){
   return Json(new { success = false });
}

return Json(students, JsonRequestBehavior.AllowGet);
}
...

I have tried the code below but it did not work. I just want to retrieve the students that are enrolled in a course, since some of them are not. Can someone help me?

1
1
1/30/2019 12:34:50 AM

Accepted Answer

You need to further build relationships in your model. The student to course relationship should be a many-to-many relationship which you are missing the proper properties in each but also a joining table and appropriate model builder (context) configuration.

Override your dbcontext model creation method to add your fluent configuration:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Build many-to-many relationships
        modelBuilder.Entity<Student>()
                      .HasMany<Course>(c => c.Courses)
                      .WithMany(s => s.Student)
                      .Map(pe =>
                      {
                          pe.MapLeftKey("Student_ID");
                          pe.MapRightKey("Course_ID");
                          pe.ToTable("StudentCoursesTable");
                      });
    }

Add missing Courses from your Student class:

    public class Students
    {
        public ICollection<Courses> Courses { get; set; } 
    }
0
1/30/2019 12:40:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow