C# linq sql联接使用查询语法获取null
在我的asp.net core mvc 3项目中,当我使用方法语法时,部门名称会显示在索引视图的表中,但当我使用查询语法时,部门名称不会显示。在调试过程中。部门为空。我不知道我的错是什么 课程和部门模式C# linq sql联接使用查询语法获取null,c#,asp.net,linq,entity-framework-core-3.1,C#,Asp.net,Linq,Entity Framework Core 3.1,在我的asp.net core mvc 3项目中,当我使用方法语法时,部门名称会显示在索引视图的表中,但当我使用查询语法时,部门名称不会显示。在调试过程中。部门为空。我不知道我的错是什么 课程和部门模式 public class Course { [Key] public int CourseId { get; set; } public string CourseName { get; set; } public int
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; }
}
.....
<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>
....
index.cshtml
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; }
}
.....
<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>
....
。。。。。
@foreach(模型中的var项目){
@DisplayFor(modelItem=>item.CourseId)
@DisplayFor(modelItem=>item.CourseName)
@DisplayFor(modelItem=>item.Credits)
@DisplayFor(modelItem=>item.Department.DepartmentName)
....
您的错误是缺少。Include()查询语法中的
语句。由于它不能作为查询语法使用,您必须混合使用这两种编写方式。我不喜欢这种混合方式,为什么我总是使用方法语法。为什么您希望它出现在第二种情况下?填充它的是EF核心特定的Include
方法,而不是方法或查询语法税务。还有为什么您需要手动加入?Department
navigation属性正好表示该加入,所以它确实是多余的。