我的项目中有以下四个实体。
学生
public int StudentID { get; set; }
public string StudentName { get; set; }
public int StandardId { get; set; }
public virtual Standard Standard { get; set; }
public virtual StudentAddress StudentAddress { get; set; }
public virtual ICollection<Course> Courses { get; set; }
老师
public int TeacherId { get; set; }
public string TeacherName { get; set; }
public Nullable<int> StandardId { get; set; }
public virtual ICollection<Course> Courses { get; set; }
public virtual Standard Standard { get; set; }
标准
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
public virtual ICollection<Teacher> Teachers { get; set; }
课程
public int CourseId { get; set; }
public string CourseName { get; set; }
public string Location { get; set; }
public int TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual ICollection<Student> Students { get; set; }
如果我尝试直接从学生实体访问课程列表,我总是将课程计数为零。
using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = (from s in db.Students
select s).FirstOrDefault<Student>();
foreach (var item in query.Courses)
{
Console.WriteLine(item.CourseName);
}
Console.ReadLine();
}
但是如果我访问下面的课程列表,我会正确获取数据,第一种方法有什么问题?我错过了什么吗?我希望下面的方法不是访问数据的有效方法。
using (SchoolDBEntities db = new SchoolDBEntities())
{
var query = (from s in db.Students
select s).FirstOrDefault<Student>();
foreach (var item in query.Standard.Teachers)
{
foreach (var crs in item.Courses)
{
Console.WriteLine(crs.CourseName);
}
}
Console.ReadLine();
}