views:

209

answers:

1

I've two tables (1:N)

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

and -

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

link between Master.idMaster and lnk.idMaster

I've a SQL query:

 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

I need to translate this T-SQL query to a Linq-to-SQL statement, preferably in C#

A: 

You cannot control the exact sql output of a Linq-to-SQL query, but this should do the trick:

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,
                      };

You would still need an other query to calculate the max(master.idMaster). Something like this:

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