Linq to Entities From vs Join

3

在使用“from”子句或“join”子句连接多对多表时,是否存在差异?返回的结果集是相同的。

例如,在一个多对多关系中包括三个表(包括一个联接表):学生、学生课程和课程:

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来测试它们。

我避免使用Include有两个原因:

  1. 我通常需要有条件地包含,因此使用上述两种技术。
  2. 根据我的了解,Include返回整个相关表,可能会影响性能。
1个回答

0

在内部,LINQ to Entities将创建两个不同的查询,其中您的第一个示例将使用WHERE,而第二个示例将连接表。但是,这对性能没有影响,因为SQL优化器将为这两个查询创建相同的执行计划。请参见Inner join vs Where

从最佳实践的角度来看,第一种选项几乎总是更可取的。使用导航属性使您的代码更易于阅读和理解,并消除了必须自己连接表的麻烦。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接