2014-01-17 79 views
2

使用'from'子句或'join'子句時加入多個表時有區別嗎?返回的結果集是相同的。Linq to實體來自vs加入

在多對多的關係(包括結表)就拿三個表:學生,StudentCourses,課程:

var query = from student in context.Students 
      from studentcourse in student.StudentCourses 
      where studentcourse.CourseID == 4 
      select student; 


var query = from student in context.Students 
      join studentcourse in context.StudentCourses 
      on student.StudentID equals studentcourse.StudentID 
      where studentcourse.CourseID == 4 
      select student; 
  1. 要麼他們是最好的做法?
  2. 表現?這個比那個好嗎?我還沒有機會到SQL Profiler中的任何一個。

我使用包括以下兩個原因避免:

  1. 我需要條件包括往往不是,因此上述兩種技術。
  2. 從我讀過的內容,包括返回整個相關的表,可能是性能的徵稅。

回答

0

在內部,LINQ to Entities將創建兩個不同的查詢,其中第一個示例將使用WHERE,第二個將加入表。但是這對性能沒有影響,因爲SQL優化器將爲這兩個查詢創建相同的執行計劃。見Inner join vs Where

明智的最佳實踐,第一個選項幾乎總是可取的。使用導航屬性使您的代碼更易於閱讀和理解,並消除了必須自己加入表格的麻煩。