linq sql join 使用查询语法获取空值

问题描述

在我的asp.net core mvc 3项目中,当我使用方法语法时,部门名称出现在索引视图的表中,但是当我使用查询语法时,部门名称不会出现。在调试过程中。部门为空。我不知道我的错是什么?

课程和部门模型

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; }
    }

课程控制器

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>
....

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)