我需要使用Linq查询获取Icollection数据以及每个记录实例的其他数据,我正在做的事情。
public partial class Course
{
public Course()
{
this.StudentCourses = new HashSet<StudentCourse>();
}
public int CourseID { get; set; }
public string Title { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
public partial class Student
{
public Student()
{
this.StudentCourses = new HashSet<StudentCourse>();
}
public int StudentID { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
public partial class StudentCourse
{
public int StudentCourseID { get; set; }
public int StudentID { get; set; }
public int CourseID { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
public void readStudents()
{
using (var db2 = new MyDbContext())
{
List<Student> _studentRead = new List<Student>();
_studentRead = (from b in db2.Students
orderby b.StudentID
select b).ToList() ;
}
}
public partial class Student
{
public Student()
{
this.StudentCourses = new HashSet<StudentCourse>();
}
public int StudentID { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
我现在得到的结果是正确的;我可以使用以下声明看到学生和他们注册的课程列表;
using (var db2 = new MyDbContext())
{
List<Student> _studentRead = new List<Student>();
_studentRead = (from _student in db2.Students.Include(r=>r.StudentCourses)
select _student).ToList();
}
现在我如何在我的linq语句中包含课程标题如果我想如下图所示我可以阅读课程
答案 0 :(得分:1)
如果您在加载学生对象时尝试加载StudentCourse集合,则可以使用Include扩展方法。
public void LoadStudents()
{
using (var db2 = new MyDbContext()
{
//Lambda Linq
var studentList = new List<Student>();
studentList = db2.Students
.Include(s => s.StudentCourses)
.OrderBy (s => s.StudentId)
.ToList();
//Comprehension Linq
var compList = new List<Student>();
compList = (from s in db2.Students.Include(r => r.StudentCourses)
OrderBy s.StudentId
Select s).ToList();
}
}
这将明确告诉上下文在从上下文加载每个学生对象时加载集合。
扩展方法位于System.Data.Entity
命名空间
可在此处找到更多信息: https://msdn.microsoft.com/en-us/data/jj574232.aspx
Upate 1 - 显示加载多个依赖对象级别
public void LoadStudents()
{
//Lambda Linq
var lambdaList = db2.Students
.Include(s => s.StudentCourses.Select(sc => sc.Course))
.OrderBy(s => s.StudentId)
.ToList();
//Comprehension Linq
var compList = (from student in db2.Students.Include(s => s.StudentCourse.Select(sc => sc.Course)
OrderBy student.StudentId
Select student).ToList();
}