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

クエリの理解として:

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
    }

メソッド構文 (「ドット表記」) の使用:

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));

このようなクエリの場合、クエリ構文は私にはずっときれいに見えます。

于 2012-09-17T13:26:15.533 に答える