I'm trying to create an ASP.NET web service that exposes a list of students and courses with the Entity Framework. Each Course is composed of multiple Students:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public ICollection<Student> Students { get; set; }
}
I am seeding the models like so:
protected override void Seed(StudentsContext context)
{
var students = new List<Student>
{
new Student { Id = 1, Name = "stu1" },
new Student { Id = 2, Name = "stu2" },
new Student { Id = 3, Name = "stu3" },
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
var courses = new List<Course>
{
new Course { Id = 1, Title = "course1",
Students = new List<Student>() { students[0], students[1] } },
new Course { Id = 2, Title = "course2",
Students = new List<Student>() { students[0] } },
new Course { Id = 3, Title = "course3" },
};
courses.ForEach(c => context.Courses.Add(c));
context.SaveChanges();
}
Visual Studio generated an ApiController for the Course with a GetCourses() method to get all the courses:
// GET api/Course
public IEnumerable<Course> GetCourses()
{
return db.Courses.AsEnumerable();
}
However, when I use the web service to get the list of courses, it returns back JSON with courses that have students set to null:
[{"Id":1,"Title":"course1","Students":null},
{"Id":2,"Title":"course2","Students":null},
{"Id":3,"Title":"course3","Students":null}]
How could I get the web service to include the list of students that are assigned to each course? Thanks in advance.
UPDATE
Slauma's fix of changing GetCourses to
public IEnumerable<Course> GetCourses()
{
return db.Courses.Include(c => c.Students).AsEnumerable();
}
partially worked. martin_costello's second solution had a similar effect. Something else I needed to do was to fix my Student class to clearly indicate the many-to-many relationship:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Course> CoursesAttending { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public ICollection<Student> Students { get; set; }
}