LINQ语法问题

时间:2011-04-21 11:50:49

标签: c# .net linq linq-to-sql

我有这个原始的SQL需要在LINQ中重写:

SELECT 
    luProfiles.luProfileID,
    luProfiles.ProfileName,
    NoOfRights = (SELECT Count(pkProfileRightsID) FROM tblProfileRights WHERE fkProfileID = luProfileID)
FROM  luProfiles 
WHERE luProfiles.ProfileName LIKE ...

我在LINQ中完成了大部分工作,但我不确定如何将NoOfRights部分添加到LINQ中。这是我到目前为止所做的:

return from p in _database.LuProfiles
       where p.ProfileName.ToLower().StartsWith(strProfile.ToLower())             
       select p; 

有人能告诉我在LINQ中包含NoOfRights部分的正确语法吗?

4 个答案:

答案 0 :(得分:3)

from p in _database.LuProfiles
let NoOfRights = (from r in database.tblProfileRights 
                  where r.fkProfileID == p.luProfileID
                  select r).Count()
where p.ProfileName.ToLower().StartsWith(strProfile.ToLower())             
select new
{
    p.luProfileID,
    p.ProfileName,
    NoOfRights 
};

答案 1 :(得分:2)

如果您使用的是LINQ-to-SQL或EF,并且设置了FK,则应该具有导航属性ProfileRights。在这种情况下,您可以这样查询:

from p in _database.LuProfiles
where p.ProfileName.ToLower().StartsWith(strProfile.ToLower())
select new 
{
    p.ProfileId,
    p.ProfileName,
    NoOfRights = p.ProfileRights.Count()
};

答案 2 :(得分:1)

我认为这会帮助你:

from l in luProfiles
where l.ProfileName.Contains(something)
select new
{
    l.luProfileID,
    l.ProfileName,
    noOfRights = tblProfileRights.Count(t => t.fkProfileID == l.luProfileID)
}

答案 3 :(得分:1)

我建议您先将SQL更改为以下内容:

SELECT 
  luProfiles.luProfileID,
  luProfiles.ProfileName,
  NoOfRights = COUNT(pkProfileRightsID)
FROM luProfiles
LEFT JOIN tblProfileRights ON fkProfileID = luProfileID
WHERE luProfiles.ProfileName like ...
GROUP BY luProfiles.luProfileID, luProfiles.ProfileName

所以这很容易转换为LINQ:

return from p in _database.LuProfiles
join o in p.Profiles on p.luProfileID equals o.fkProfileID
group p by new { p.luProfileID, p.ProfileName } into g
select new { g.Key.luProfileID, g.Key.ProfileName , g.Count() }

(未经过测试,请亲自动手)