使用“from”子句或“join”子句连接多对多表时有区别吗?返回的结果集是相同的。
以多对多关系中的三个表(包括联结表)为例:Students、StudentCourses、Courses:
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;
- 它们中的任何一个都是最佳实践吗?
- 性能?这个比那个好吗?我还没有机会使用 SQL Profiler。
我避免使用 Include 有两个原因:
- 我经常需要条件包含,因此需要上述两种技术。
- 据我所知,Include 会返回整个相关表,这可能会影响性能。
最佳答案
在内部,LINQ to Entities 将创建两个不同的查询,您的第一个示例将使用 WHERE,第二个示例将连接表。然而,这对性能没有影响,因为 SQL 优化器将为这两个查询创建相同的执行计划。参见 Inner join vs Where
明智的最佳做法,第一个选项几乎总是可取的。使用导航属性使您的代码更易于阅读和理解,并消除了必须自己加入表的麻烦。
关于entity-framework - Linq to Entities From vs Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177504/