2017-04-20 106 views
0

我有以下Linq查詢獲取下面的錯誤。我的問題是如何在where子句中使用T_EquipmentCompetency.Competency,但是在group by或select列表中沒有它。我對LINQ查詢相當陌生。有什麼我在這裏失蹤?C#LINQ查詢與group by,有和where子句無效

using (EntitiesModel dbContext = new EntitiesModel()) 
     { 
      var competencyForMachine = (from eq in dbContext.T_Equipmentcompetencies 
       where eq.MachineId == machineId 
       select eq.CompetencyId); 

      var competencyForEmployees = (from sm in dbContext.T_OHS_Skillsmatrices 
       join em in dbContext.T_Employees on sm.EmployeeID equals em.EmployeeID 
       where competencyForMachine.Contains(sm.CompentencyID) 
       group sm by new {sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR} into g 
       where g.Count() == competencyForMachine.Count() 
       select new {g.Key.EmployeeID, g.Key.FirstNameSTR,g.Key.LastNameSTR}); 

      foreach(var employee in competencyForEmployees) 
      { 
       RadMenuItem employeeItem = new RadMenuItem { Text= employee.FirstNameSTR + " " + employee.LastNameSTR, Value = employee.EmployeeID.ToString()}; 
       Item.Items.Add(employeeItem); 
      } 
     } 

這是我得到

Telerik.OpenAccess.RT.sql.SQLException: Column 
'dbo.T_EquipmentCompetency.CompetencyId' is invalid in the select list 
because it is not contained in either an aggregate function or the GROUP BY clause. 

在SQL的錯誤,我試圖仿效在SQL Server

declare @MachineId int = 1      
select sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR 
from T_OHS_SkillsMatrix sm 
inner join T_Employees em on sm.EmployeeID = em.employeeId 
where sm.CompentencyID in ( select CompetencyID 
          from T_EquipmentCompetency 
          where MachineId = @machineId 
         ) 
group by sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR 
having count(*) = (select count(*) from T_EquipmentCompetency where MachineId = @MachineId) 
+0

我修復了下面列出的拼寫錯誤,但我仍然遇到同樣的問題。 –

回答

1

的作品,你得到它的拼寫錯誤

select eq.CompetencyId --- different spelling 

sm.CompentencyID   

而在sql sql server

where sm.CompentencyID in ( select CompentencyID 
+0

謝謝我糾正了拼寫錯誤。問題依然存在,問題依然存在。我仍然在sql server中得到結果,但在LINQ C#中的上述錯誤# –

+0

那麼現在有什麼錯誤?你可以發佈你的更新腳本 – maSTAShuFu

+0

錯誤是一樣的。我在SQL Server腳本中編輯了拼寫錯誤。很顯然,在LINQ查詢中,我在sm和eq之間有兩種不同的拼寫,但它們反映了數據庫表列。 –