2016-09-26 109 views
1

如何將left join轉換爲linq腳本。我有一個T-SQL這樣的:
如何將左連接SQL腳本轉換爲Linq腳本?

SELECT 
    es.StandardID, 
    COUNT(DISTINCT esc.StandardCourseID) AS CourseIDCount, 
    COUNT(DISTINCT esp.StandardPostID) AS PostIDCount 
FROM EduStandards AS es 
LEFT JOIN EduStandardCourses AS esc 
    ON es.StandardID = esc.StandardID 
LEFT JOIN EduStandardPosts AS esp 
    ON es.StandardID = esp.StandardID 
GROUP BY es.StandardID 

,我想這個轉換爲LINQ。

回答

0

以下是左連接的查詢,它是您在linq中查詢的副本。

var query = (from es in dbContext.EduStandards 
        join esc in dbContext.EduStandardCourses on es.StandardID equals esc.StandardID into ssc 
        from esc in ssc.DefaultIfEmpty() 
        join esp in dbContext.EduStandardPosts on es.StandardID equals esp.StandardID into ssp 
        from esp in ssp.DefaultIfEmpty() 
        select new { StandardId = es.StandardID, CourseCount = ssc.Count(), PostCount = ssp.Count() }).Distinct().ToList(); 

但我認爲,我們需要不適用左連接在LINQ to計算計數。優化後的linq查詢將返回相同的結果。

var query2 = (from es in dbContext.EduStandards 
        join esc in dbContext.EduStandardCourses on es.StandardID equals esc.StandardID into ssc 
        join esp in dbContext.EduStandardPosts on es.StandardID equals esp.StandardID into ssp 
        select new { StandardId = es.StandardID, CourseCount = ssc.Count(), PostCount = ssp.Count() }); 
0

這是我想出來的

var query = from es in db.EduStandards 
      join esc1 in db.EduStandardCourses 
      on es.StandardId equals esc1.StandardId into esc 
      from c in esc.DefaultIfEmpty() 
      join esp1 in db.EduStandardPosts 
      on es.StandardId equals esp1.StandardId into esp 
      from p in esp.DefaultIfEmpty() 
      group new { es.StandardId, Course = c, Post = p } by es.StandardId into g 
      select new 
      { 
       StandardId = g.Key, 
       CourseIdCount = g.Where(x => x.Course != null).Count(), 
       PostIdCount = g.Where(x => x.Post != null).Count(), 
      }; 

不過,我不能完全肯定是否會爲EF工作。

你總是可以做這樣的事情:

var query = from es in db.EduStandards 
      select new 
      { 
       es.StandardId, 
       CourseIdCount = db.EduStandardCourses.Where(esc => esc.StandardId == es.StandardId).Distinct().Count(), 
       PostIdCount = db.EduStandardPosts.Where(esp => esp.StandardId == es.StandardId).Distinct().Count() 
      }; 

另外,我無法證實這些查詢的任何一個表現,由於缺乏對數據庫的瞭解的。