C#LINQ使用group by,having和where子句进行查询无效

时间:2017-04-20 02:05:07

标签: c# sql linq telerik

我有以下Linq查询,它们收到以下错误。我的问题是我如何在where子句中使用T_EquipmentCompetency.Competency但不在group by或select列表中使用它。我对LINQ查询还不熟悉。我在这里找不到什么东西吗?

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)

1 个答案:

答案 0 :(得分:1)

你搞错了

select eq.CompetencyId   --- different spelling

sm.CompentencyID         

在sql sql server中

where sm.CompentencyID in  (    select  CompentencyID