LINQ:如何介绍包含在哪里?

时间:2015-07-16 18:54:10

标签: c# linq

我有这个问题,我用来吸引学生,我也希望包括学生正在学习的当前课程。如何更改此查询以使其正常工作?

var students = Context.Students
                      .Where(x=>x.Race == "SomeRace")
                      .Include(x=> x.StudentCourse.FirstOrDefault(x=>x.Status == CourseStatus.Current))

此查询将通过错误,因为EF不允许在Include中放置where条件。任何转身?还有其他任何方式来编写此查询吗?

更新: 如果我使用@CoryNelson提出的解决方案,就像这样:

studentResult = Context.Students
.Where(x=>x.Race == "SomeRace")
.Select(x=>new
{
    Student = x,
    CurrentCourse = x.StudentCourse
        .FirstOrDefault(y=>y.Status == CourseStatus.Current)
};

我得到的studentResult不是一个列表,就像我尝试做的那样

foreach( student in studentResult) 
{ 
   finalResult.Add( 
   new StudentDto
  { 
      FirstName = student.Firstname // I do not get student first name, intellisense is not letting me select FirstName, which means studentResult is not a collection? 
   } 
} 

2 个答案:

答案 0 :(得分:3)

您使用Include错误。 Include用于强制在连接到您要带回的实体的实体上进行预先加载。有关Include的更多信息,请查看here

您要做的事情应该是where语句以及其他选择标准。

<强>更新

然后你确实想使用Cory Nelson的LINQ查询。

var students = Context.Students
                      .Where(x => x.Race == "SomeRace")
                      .Select(x => new
                      {
                          Student = x,
                          CurrentCouse = x.StudentCourse.FirstOrDefault(y => y.Status == CourseStatus.Current)
                      });

然后,为了访问它们,您可以执行以下操作:

foreach(var s in students)
{
    finalResult.Add(new StudentDto { FirstName = s.Student.Firstname } );
}

new中使用Select可创建anonymous type。通过说Student = x,您说匿名类型有一个名为Student的字段,该字段将具有x类的原始变量Student的字段。提供的文章提供了有关匿名类型的更多详细信息,但您只需访问这些字段即可。

答案 1 :(得分:1)

Context.Students .Where(x=>x.Race == "SomeRace") .Select(x=>new { Student = x, CurrentCourse = x.StudentCourse .FirstOrDefault(y=>y.Status == CourseStatus.Current) }; 带来全部或全部导航属性。您可能希望使用投影:

SELECT TO_CHAR(yoh.createts, 'YYYY-MM-DD HH24') AS SysHour