Skip to main content

Lesson 6 of 8

Raw SQL, Stored Procedures & Performance Tuning

Sometimes LINQ can't express complex queries efficiently - full-text search, window functions, recursive CTEs. EF Core allows raw SQL while still mapping results to entity types, preventing SQL injection via parameterization.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Raw SQL & Performance Diagnostics

Raw SQL & Performance Diagnostics
// ━━ Stored procedure call ━━
var products = await dbContext.Products
    .FromSqlRaw("EXEC sp_GetProductsByCategory @CategoryId = {0}, @Limit = {1}",
        categoryId, 50)
    .AsNoTracking()
    .ToListAsync(ct);

// ━━ Window functions (SQL Server) via raw SQL ━━
var ranked = await dbContext.Database
    .SqlQuery<ProductRankDto>($"""
        SELECT
            Id,
            Name,
            Price,
            CategoryId,
            RANK() OVER (PARTITION BY CategoryId ORDER BY Price DESC) AS PriceRank
        FROM Products
        WHERE IsDeleted = 0
        """)
    .Where(p => p.PriceRank <= 3)  // top 3 per category - filter applied in memory (small result)
    .ToListAsync(ct);

// ━━ EF Core interceptor - log slow queries ━━
public class SlowQueryInterceptor(ILogger<SlowQueryInterceptor> logger)
    : Microsoft.EntityFrameworkCore.Diagnostics.DbCommandInterceptor
{
    public override async ValueTask<Microsoft.EntityFrameworkCore.Diagnostics.DbDataReader> ReaderExecutedAsync(
        System.Data.Common.DbCommand command,
        Microsoft.EntityFrameworkCore.Diagnostics.CommandExecutedEventData eventData,
        Microsoft.EntityFrameworkCore.Diagnostics.DbDataReader result,
        CancellationToken ct = default)
    {
        if (eventData.Duration.TotalMilliseconds > 500)
        {
            logger.LogWarning(
                "SLOW QUERY ({Duration}ms): {Sql}",
                eventData.Duration.TotalMilliseconds,
                command.CommandText[..Math.Min(500, command.CommandText.Length)]);
        }

        return await base.ReaderExecutedAsync(command, eventData, result, ct);
    }
}

// Register interceptor:
builder.Services.AddDbContextPool<AppDbContext>(options =>
    options.UseSqlServer(connectionString)
           .AddInterceptors(new SlowQueryInterceptor(/* logger */)));

// ━━ EF Core performance tips ━━
// 1. Always AsNoTracking() for reads
// 2. Always Select() to project - never return full entities to API
// 3. Use Skip/Take for pagination, not LINQ .ToList().Skip()
// 4. ExecuteUpdate/ExecuteDelete for bulk ops (no entity loading)
// 5. Compiled queries for hot paths
// 6. AsSplitQuery() for multi-Include queries
// 7. DbContext pooling (AddDbContextPool instead of AddDbContext)
// 8. connection resilience (EnableRetryOnFailure)

record ProductRankDto(Guid Id, string Name, decimal Price, Guid CategoryId, int PriceRank);

Tip

Tip

Practice Raw SQL Stored Procedures Performance Tuning in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Raw SQL Stored Procedures Performance Tuning from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Raw SQL Stored Procedures Performance Tuning is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done