in my asp.net core mvc 3 project, when I use method syntax, the department name appears in the table on index view, but when I use the query syntax, the department name does not appear. On debugging course.Department comes null. I can't figure out what is my fault?
Course and Department model
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public int Credits { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public decimal Budget { get; set; }
public ICollection<Course> Courses { get; set; }
}
CourseController
public IActionResult Index()
{
//method syntax
//var courses = _context.Courses.Include(x=>x.Department).ToList();
//query syntax
var courses = from course in _context.Courses
join dept in _context.Departments on course.DepartmentId equals dept.DepartmentId
select course;
return View(courses);
}
index.cshtml
.....
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CourseId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Credits)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.DepartmentName)
</td>
</tr>
....