2

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.

1 Answer 1

1

You need to 'include' the navigation property in the query...

Student s = rep.Students.Include("Courses").First(x => x.Id == id);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but as far as I am trying there is no "Include" method I can use in there. Are you sure about it?
I assumed that Student was a DbSet and that EFStudentRepository was a DbContext and hence you were running a Linq to Entities query.
The EFStudentRepository is a class in which I instantiate an EFDbContext which returns Students as IEnumerable.
In that case I would add a method that takes the identifier of the student you want and then in the method it recovers the specific student along with the Include needed to get the related courses. Then return that from the method to the caller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.