1

我需要选择结果集中每个州和州表的所有列的城市计数。我有 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# 语言,但我们将不胜感激

4

2 回答 2

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 参数。

于 2012-04-29T09:55:26.627 回答
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});
于 2012-04-29T08:23:31.420 回答