AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Optimize and simplify EFCore database request for ContosoUniversity/Pages/Instructors/Index.cshtml.cs page

Open zxcq544 opened this issue 3 years ago • 1 comments

Hello. This fix is about tutorial at this page https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/read-related-data?view=aspnetcore-6.0 Line 224 of this file https://github.com/dotnet/AspNetCore.Docs/edit/main/aspnetcore/data/ef-rp/read-related-data.md Which leads to source code located here https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/data/ef-rp/intro/samples/cu50/Pages/Instructors/Index.cshtml.cs at line 47. Currently inside Instructors/Index.cshtml.cs we have code which looks like that

if (courseID != null)
{
    CourseID = courseID.Value;
    var selectedCourse = InstructorData.Courses
        .Where(x => x.CourseID == courseID).Single();
    await _context.Entry(selectedCourse)
                  .Collection(x => x.Enrollments).LoadAsync();
    foreach (Enrollment enrollment in selectedCourse.Enrollments)
    {
      await _context.Entry(enrollment).Reference(x => x.Student).LoadAsync();
    }
    InstructorData.Enrollments = selectedCourse.Enrollments;
}

This code makes several database requests and some of them are done inside foreach loop, which is not optimal for the data which it gets. This code could be replaced with this one:

if (courseID != null)
{   
    CourseID = courseID.Value;                
    IEnumerable<Enrollment> Enrollments = await _context.Enrollments.Where(x => x.CourseID == CourseID)                    
        .Include(i=>i.Student)
        .ToListAsync();                 
    InstructorData.Enrollments = Enrollments;
}

The difference is that instead of doing 1 request to get Enrollment and then doing requests in a loop to get related students we make 1 request with INNER JOIN which gets all related students without foreach loop. And it fixes typo with courseID which should be CourseID


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

zxcq544 avatar Aug 10 '22 13:08 zxcq544

@tdykstra @JeremyLikness please review.

Rick-Anderson avatar Aug 10 '22 21:08 Rick-Anderson

@zxcq544 Thanks for your suggestion. I agree this will be an improvement.

tdykstra avatar Aug 11 '22 17:08 tdykstra