实体框架5中相关实体集合的问题

时间:2013-08-28 17:47:07

标签: .net entity-framework

我的项目中有四个实体。

学生

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

0 个答案:

没有答案