I am new to using Asp.Net MVC 5 Web Api2 and I am developing a very small sample in which I've faced a weird issue. I have two very simple entity classes, "Student" and "Course" and each one of them has a "virtual ICollection" reference to the other one (making their relationship many-to-many). the code below shows the Student entity and the Course entity is very similar, and it refers to the student class.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int AdmissionYear { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
I also have this small Api Controller:
public class StudentController : ApiController
{
private EFStudentRepository rep = new EFStudentRepository();
public IEnumerable<Student> Get()
{
return rep.Students;
}
public Student Get(int id)
{
Student s = rep.Students.First(x => x.Id == id);
if (s == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return s;
}
}
The problem is, when I run the app and invoke this controller, the json output shows the data for the student but does not show the courses that are associated with that student, something like this:
{"ID":1, "Name":"Mikel", "AdmissionYear":2010, "Courses":null}
While in fact in the database, the "StudentCourse" table has been automatically created and I have also filled it with proper data. It is especially weird as when I write a normal controller that renders HTML, all the data properly shows up, but in case of the Api controller it doesn't. So basically it does show the Master record's data but not it's detail records' data.
Thanks in advance.