2012-07-20 115 views
2

我的應用程序中有一個實體框架4模型。我需要它來生成的SQL語句:如何爲以下SQL編寫實體框架4查詢?

SELECT * 
FROM  Reads   AS R 
INNER JOIN Images   AS I ON R.ReadId = I.ReadId AND I.ImageTypeId = 2 
LEFT OUTER JOIN Alarms  AS A ON R.ReadId = A.ReadId AND A.DomainId IN (103,102,101,2,1,12) AND A.i_active = 1 
LEFT OUTER JOIN ListDetails AS L ON L.ListDetailId = A.ListDetailId 
WHERE R.i_active = 1 

這是我現在有這個查詢在我的代碼:

var items = from read in query 
      join plate in context.Images  on read.ReadId  equals plate.ReadId 
      join temp1 in context.Alarms  on read.ReadId  equals temp1.ReadId  into alarms from alarm in alarms.DefaultIfEmpty() 
      join temp2 in context.ListDetails on alarm.ListDetailId equals temp2.ListDetailId into entries from entry in entries.DefaultIfEmpty() 
      where plate.ImageTypeId == 2 && plate.IActive == 1 
      select new { read, plate, alarm, entry.OfficerNotes }; 

如何修改實體框架查詢來獲取SQL查詢,我需要?

回答

2

對於左連接 - 我建議使用帶有where代替join一個from,我覺得它使清潔

對於內部有多個加盟加盟條件 - 你需要加入兩個匹配的匿名類型,或使用一個fromwhere條件

對於X IN列表,你需要指定列表中的查詢外,使用Any方法或Contains方法

List<int> domainIds = new List<int>() { 103,102,101,2,1,12 }; 

    var items = from read in query 
       join plate in context.Images 
       on new { read.ReadId, ImageTypeId = 2 } equals new { plate.ReadId, plate.ImageTypeId } 
       from alarm in context.Alarms 
            .Where(x => x.IActive == 1) 
            .Where(x => domainIds.Any(y => y == x.DomainId)) 
            .Where(x => read.ReadId == x.ReadId) 
            .DefaultIfEmpty() 
       from entry in context.ListDetails 
            .Where(x => alarm.ListDetailId == x.ListDetailId) 
            .DefaultIfEmpty() 
       select new { read, plate, alarm, entry.OfficerNotes }; 
+0

謝謝!我對代碼進行了這些更改,它們完美地工作!但是,我在域ID測試中使用了「Contains」。 – 2012-07-20 15:59:24

+0

我會推薦使用Contains而不是Any。包含產生乾淨IN語句,而在任何產生可怕EXISTS(SELECT 1 AS [C1] FROM(SELECT ... 103 AS [C1] FROM(SELECT 1 AS X)AS [SingleRowTable1] UNION ALL SELECT 102 AS [C1] FROM( SELECT 1 AS X)AS [SingleRowTable2])AS [UnionAll1],其中[UnionAll1] [C1] = [Extent3] [域ID]) – Ruslan 2012-07-20 16:00:00

+0

@Ruslan - 。在這種情況下,你可能是正確的 - 'Contains'更好。我喜歡用'Any',因爲它允許更復雜的條件 – Aducci 2012-07-20 16:04:01