0

我有两张桌子 (1:N)

CREATE TABLE master (idMaster int identity (1,1) not null,
 TheName varchar( 100) null,
 constraint pk_master primary key(idMaster) clustered)

和 -

CREATE TABLE lnk (idSlave int not null,
 idMaster int not null,
 constraint pk_lnk_master_slave(idSlave) primary key clustered)

Master.idMaster 和 lnk.idMaster 之间的链接

我有一个 SQL 查询:

 select max (master.idMaster) as idMaster,
        master.theName,
        count (lnk.idSlave) as freq
  from lnk 
  inner join master ON lnk.idMaster = master.idMaster
  Group by master.theName
  order by freq desc, master.theName

我需要将此 T-SQL 查询转换为 Linq-to-SQL 语句,最好在 C# 中

4

1 回答 1

0

您无法控制 Linq-to-SQL 查询的确切 sql 输出,但这应该可以解决问题:

var results = from slave in dataContext.lnks
                  group slave by slave.idMaster
                      into slaveByMaster
                        let count = slaveByMaster.Count()
                      orderby count
                      select new
                      {
                          slaveByMaster.Key,
                          count,
                      };

您仍然需要其他查询来计算最大值(master.idMaster)。像这样的东西:

            var result2 = (from master in dataContext.masters
                       select master.idMaster).Max();
于 2010-03-10T11:06:35.240 回答