将SQL查询转换为LINQ

时间:2012-04-29 08:11:00

标签: c# linq tsql

我需要城市计数每个州和所有州列表中的选择结果集。 我有TSQL查询,但不知道如何在LINQ中处理内部查询和分组。

州表

StateID,StateName,Description,Address,SectionName

城市表:

CityID,StateID,Address,Description

这里需要将TSQL查询转换为LINQ

declare @State varchar(100)
set @State='IL'

SELECT s.*,oCities.CityCount
from ( 
        Select c.StateID,count(*) CityCount
        from States s inner join Cities c on 
        s.StateID =c.StateID 
        where s.StateName =@State
        group by c.StateID 
    ) oCities inner join States s on oCities.StateID = s.StateID 
where s.StateName =@State

最好是C#语言,但任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

假设您的外键已被正确定义和导入,那么这样的东西应该可以正常工作

var state = states.Where (s => s.StateName == name).Select (
    s => new {State=s, CityCount=s.Cities.Count()}).SingleOrDefault ();

使用Linq to SQL将其翻译为

SELECT [t2].*, [t2].[value] AS [CityCount]
FROM (
    SELECT [t0].*, (
        SELECT COUNT(*)
        FROM [City] AS [t1]
        WHERE [t1].[StateId] = [t0].[Id]
        ) AS [value]
    FROM [State] AS [t0]
    ) AS [t2]
WHERE [t2].[StateName] = @p0

其中p0是你的@state参数。

答案 1 :(得分:2)

var q1 = 
from c in cities
join s in states 
on c.StateID equals s.StateID
where s.StateName=statename
select new {city=c, state=s};

var result = q1.GroupBy(x=>x.state.StateID)
                .Select(x=>new {Count = x.Count(), state = x.First().state});