Linq to sql 将存储过程转换为Linq2SQL(计数、最大值、组、orderby)

Linq to sql 将存储过程转换为Linq2SQL(计数、最大值、组、orderby),linq-to-sql,count,group-by,inner-join,max,Linq To Sql,Count,Group By,Inner Join,Max,我有两张桌子 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(

我有两张桌子

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

中,您无法控制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,
                      };
您仍然需要另一个查询来计算maxmaster.idMaster。大概是这样的:

            var result2 = (from master in dataContext.masters
                       select master.idMaster).Max();