Course contentsShow
← C#
Lesson 1364 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Optimizing Database Access for SSR

Utilize Compiled EF Core queries to speed up server-side page generation.

In this lesson, you will learn how to leverage Compiled EF Core queries to eliminate the overhead of query translation and significantly speed up your Server-Side Rendering (SSR) page generation.

The Cost of Query Compilation

Every time you execute a LINQ query against your database, Entity Framework Core must perform a process called "compilation." It analyzes your LINQ expression tree, generates the corresponding SQL, and manages the execution plan. While EF Core caches these plans automatically, complex queries can still incur a small performance penalty during the translation phase. When you are rendering a page on the server (SSR), every millisecond counts toward reducing your Time to First Byte (TTFB).

Using Compiled Queries

By using EF.CompileQuery, you can manually compile your query once and reuse the delegate across your entire application lifecycle. This bypasses the expression tree translation entirely, providing a meaningful performance boost for frequently accessed data in your Razor components.

Here is how you define a static compiled query:

public static class UserQueries
{
    private static readonly Func<MyDbContext, int, Task<User?>> GetUserById =
        EF.CompileAsyncQuery((MyDbContext context, int id) => 
            context.Users.FirstOrDefault(u => u.Id == id));

    public static async Task<User?> GetUserAsync(MyDbContext context, int id)
    {
        return await GetUserById(context, id);
    }
}

By defining the query as a static field, you ensure it is compiled only once when the application starts. In your Blazor component or Razor page, you simply call the wrapper method, passing in your current DbContext.

Why This Matters for SSR

In an SSR scenario, your component needs to fetch data before the HTML can be sent to the browser. If your page handles a high volume of traffic, the cumulative time spent re-translating LINQ queries can create a bottleneck. Compiled queries are most effective for "hot paths"—the specific data lookups that happen on every page load, such as fetching a user profile or retrieving site-wide configuration settings. By pre-compiling these, you shave off the execution overhead, leading to snappier, more responsive server-rendered pages.

Key Takeaway: Use EF.CompileAsyncQuery for your most frequent database operations to minimize query translation time and improve SSR performance.