AspNetCore.Docs
AspNetCore.Docs copied to clipboard
Optimize and simplify EFCore database request for ContosoUniversity/Pages/Instructors/Index.cshtml.cs page
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.
- ID: d0026f69-7e5d-0d3e-5586-16ecc0656ff0
- Version Independent ID: 3cb264da-2ff1-1256-572f-aa4ebca6e255
- Content: Part 6, Razor Pages with EF Core in ASP.NET Core - Read Related Data
- Content Source: aspnetcore/data/ef-rp/read-related-data.md
- Product: aspnet-core
- Technology: aspnetcore-data
- GitHub Login: @Rick-Anderson
- Microsoft Alias: riande
@tdykstra @JeremyLikness please review.
@zxcq544 Thanks for your suggestion. I agree this will be an improvement.