2012-09-17 55 views
1

如何將以下sql查詢轉換爲dot概念linq查詢?將SQL轉換爲Dot Notion 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))) 
+1

什麼是「點概念」? –

+0

你有嘗試過嗎? –

+0

[see this](http://stackoverflow.com/questions/630045/linq-dot-notation-vs-query-expression) – ericyoung

回答

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

對於這樣的查詢,查詢語法看上去非常清潔劑我。

+0

不知道爲什麼,但它獲取所有的數據,而不是我想要的。 – ericyoung

+0

哪個查詢?換句話說,你期望查詢獲取?這應該獲取所有匹配的ID /型號/串行值,以便串行與多個設備相關聯。 –

+0

在查詢理解中存在一個會讓它無法編譯的拼寫錯誤,所以我假設你使用了方法語法。我會檢查一下。 –