0

如何将以下 sql 查询转换为点概念 linq 查询?

 SELECT     f1.device_id, f1.device_model, f2.main_serial_number
 FROM       Device AS f1 
 INNER JOIN MainSerialNumber AS f2 ON f1.device_id = f2.device_id
 WHERE      (f2.main_serial_number IN
                (SELECT    f2_1.main_serial_number
                 FROM      Device AS f1_1 
                 INNER JOIN MainSerialNumber AS f2_1 
                         ON f1_1.device_id = f2_1.device_id
                 GROUP BY f2_1.main_serial_number
                 HAVING    (COUNT(f2_1.main_serial_number) > 1)))
4

1 回答 1

1

As a query comprehension:

var serialNumbers =
    from sn in MainSerialNumber
    join dev in Device
        on sn.DeviceId equals dev.DeviceId
        into devices
    where devices.Count() > 1
    select sn.MainSerialNumber;

var result =
    from dev in Device
    join sn in MainSerialNumber
        on dev.DeviceId equals sn.DeviceId
    where serialNumbers.Contains(sn.MainSerialNumber)
    select new {
        dev.DeviceId,
        dev.DeviceModel,
        sn.MainSerialNumber
    }

Using method syntax ("dot notation"):

var serialNumbers = MainSerialNumber
    .GroupJoin(Device,
        sn  => sn.DeviceId,
        dev => dev.DeviceId,
        (sn, devs) => new
        {
            Serial = sn.MainSerialNumber,
            Count  = devs.Count()
        }
    )
    .Where(x => x.Count > 1)
    .Select(x => x.Serial);

var result = Device
    .Join(MainSerialNumber,
        dev => dev.DeviceId,
        sn  => sn.DeviceId,
        (dev, sn) => new
        {
            dev.DeviceId,
            dev.DeviceModel,
            sn.MainSerialNumber
        }
    )
    .Where(x => serialNumbers.Contains(x.MainSerialNumber));

For a query like this, the query syntax looks a lot cleaner to me.

于 2012-09-17T13:26:15.533 回答