'where子句'中的未知列'Project1.ID'

时间:2016-02-10 09:43:21

标签: c# mysql entity-framework linq linq-to-entities

我有以下表格

+--------+     +---------+     +---------+
| Class  |1   N| Student |1   N|  Test   |
+--------+<--->+---------+<--->+---------+
|ClassID |     |ClassID  |     |TestID   |
|Desc    |     |StudentID|     |StudentID|
+--------+     |Name     |     |Name     |
               +---------+     |Score    |
                               +---------+ 

我需要确定一个班级第一个学生的总分。这个学生可以有一个,多个或没有现成的测试

所以结果看起来应该是

ClassDesc | StudentName | ScoreCount
----------+-------------+-----------
C1        | Max         |        201
C2        | Tom         |       null 

我有以下代码

using (myEntities ctx = new myEntities())
{
var Reslut = ctx.Class
        .Select(x => new 
        {
        ClassDesc = x.Desc,
        StudentName = x.Student.FirstOrDefault().Name,
        ScoreCount = x.Student.FirstOrDefault().Test.Sum(t => t.Score) //Error here
        }).ToList();
}

但它给了我错误

  

'where子句'

中的未知列'Project1.ClassID'

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

var result = (from cls in ctx.Class
                           join stdt in ctx.Student on cls.ClassID equals stdt.ClassID                             
                           select new
                           {
                                  ClassDesc = cls.Desc,
                                  StudentName = stdt.Name,
                                  ScoreCount = stdt.Test.Sum(t => t.Score)
                           }).ToList();

哪个应该生成类似于以下内容的SQL:

SELECT   
    Class.ClassID,   
    Class.[Desc],  
    Student.Name,  
    (  
       SELECT  
            SUM(Test.Score)  
            FROM dbo.Test  
            WHERE Student.StudentID = Test.StudentID  
    ) AS ScoreSum  
    FROM  dbo.Class  
    INNER JOIN dbo.Student ON Class.ClassID = Student.ClassID