我的数据库中有多对多的关系。我正在使用Entity Framework发送查询。
我的课程是Student
,Course
和StudentCourse
。
public IHttpActionResult Get()
{
var data = context.Students;
return Ok(data);
}
我创建了一个查询拦截器来查看发送到数据库的查询。
Intercepted on: ReaderExecuted :- IsAsync: False, Command Text: SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name]
FROM [dbo].[Student] AS [Extent1]
Intercepted on: ReaderExecuted :- IsAsync: False, Command Text: SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name]
FROM [dbo].[Student] AS [Extent1]
Intercepted on: ReaderExecuted :- IsAsync: False, Command Text: SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Name] AS [Name]
FROM [dbo].[Course] AS [Extent1]
INNER JOIN [dbo].[Courses] AS [Extent2] ON [Extent1].[CourseId] = [Extent2].[Id]
WHERE [Extent1].[CourseId] = @EntityKeyValue1
Intercepted on: ReaderExecuted :- IsAsync: False, Command Text: SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Name] AS [Name]
FROM [dbo].[Course] AS [Extent1]
INNER JOIN [dbo].[Courses] AS [Extent2] ON [Extent1].[CourseId] = [Extent2].[Id]
WHERE [Extent1].[StudentId] = @EntityKeyValue1
....
...
...
它发送14个查询以从服务器获取关系数据。这是多行数据的性能问题吗?
答案 0 :(得分:2)
我认为你正在看到所谓的延迟加载。基本上会发生的是向db发出查询以获取所有学生。然后,当发送响应时,遍历学生集合并将StudentCourses加载到每个学生,一次一个查询。然后,当每个学生发回学生课程时,会加载课程属性(一次一个),然后发回。
您应该尝试禁用延迟加载并使用预先加载来与学生一起加载StudentCourses和Courses。像这样:
context.Students.Include(s=>s.StudentCourses).Include(s=>s.StudentCourses.Select(sc=>sc.Course)