I have two classes that are connected by using the virtual keyword:
Student:
public class Student
{
public int StudentId{get; set;}
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual IEnumerable<Enrollment> Enrollments { get; set; }
}
Enrollment:
public class Enrollment
{
public int EnrollmentId { get; set; }
public int CourseId { get; set; }
public int StudentId { get; set; }
public decimal? Grade { get; set; }
public virtual Course course { get; set; }
public virtual Student student { get; set; }
}
Both tables are populated, and have corresponding records (for instance, there is a student with id 1 and enrollments for student with id 1).
I'm pulling up a student by it's id and sending it to a view
Student student = db.Students.Find(id);
return View(student);
In the view I can display the details for that student. The @Model
does contain an Enrollment
property (at least it comes up in intellisense and doesn't red-line), but it is Null
.
There is also a course class:
{
public int CourseId { get; set; }
public String CourseName { get; set; }
public int TotalCredits { get; set; }
}
Since @Model.Enrollments
is Null
, I can't access @Model.Enrollment.CourseNamae
.
Edit: I just tried a hack workaround:
IEnumerable<Student> temp = db.Students.Include(s => s.Enrollments);
Student student = temp.FirstOrDefault(s => s.StudentId.Equals(id));
return View(student);
This is giving me the error on the second line:
System.InvalidOperationException: A specified Include path is not valid. The EntityType 'MyFirstProject2.Models.Student' does not declare a navigation property with the name 'Enrollments'.
Does that offer any clues?