I'm just starting out with some entity framework exploration, I figured it was time to see what everybody was complaining about. I am running into an issue where the entities don't seem to be returning any of the object context. I generated the model from a database with three tables which link to one another.
Courses
Instructors
CanTeach
Relationships are as you would expect: a course can relate to multiple CanTeach entities and an instructor can also relate to multiple CanTeach entities. I also added an OData service to my project which also makes use of the same model. So I can run queries like
from a in CanTeach
where a.Instructor.FirstName == "Barry"
select new { Name = a.Instructor.FirstName + " " + a.Instructor.LastName,
Course = a.Course.Name}
without issue against the OData endpoint using LINQPad. However when I do a simple query like
public Instructor GetInstructorFromID(int ID)
{
return context.Instructors.Where(i => i.ID == ID).FirstOrDefault();
}
The CanTeach list is empty. I know everything in EF is lazy loaded and it is possible that my context is out of scope by the time I look at the object context, however even trying to get the object context as soon as the query is run results in and empty object context.
What am I doing wrong?
Edit:
In addition to the answer below I found that
return context.Instructors.Include("CanTeach").Where(i => i.ID == ID).FirstOrDefault();
worked for those looking for more of a fluent API.