See exactly what SQL queries Entity Framework Core generates from your LINQ expressions
EF Core translates LINQ queries into SQL. Understanding the generated SQL helps you: identify performance issues, verify index usage, debug unexpected behavior, and optimize complex queries.
DemoProducts.Where(p => p.Price > 100).Take(10)
DECLARE @__p_0 int = 10;
SELECT TOP(@__p_0) [d].[Id], [d].[Category], [d].[CreatedDate], [d].[Description], [d].[IsActive], [d].[Name], [d].[Price], [d].[Rating], [d].[ReviewCount], [d].[SKU], [d].[StockQuantity]
FROM [DemoProducts] AS [d]
WHERE [d].[Price] > 100.0
DemoProducts.GroupBy(p => p.Category).Select(g => new { Category = g.Key, Count = g.Count() })
SELECT [d].[Category], COUNT(*) AS [Count]
FROM [DemoProducts] AS [d]
GROUP BY [d].[Category]
DemoProducts.Where(p => p.IsActive).OrderBy(p => p.Rating).ThenBy(p => p.Price).Take(20)
DECLARE @__p_0 int = 20;
SELECT TOP(@__p_0) [d].[Id], [d].[Category], [d].[CreatedDate], [d].[Description], [d].[IsActive], [d].[Name], [d].[Price], [d].[Rating], [d].[ReviewCount], [d].[SKU], [d].[StockQuantity]
FROM [DemoProducts] AS [d]
WHERE [d].[IsActive] = CAST(1 AS bit)
ORDER BY [d].[Rating], [d].[Price]
var query = _context.Products
.Where(p => p.Price > 100)
.OrderBy(p => p.Name);
// Get the SQL before executing
string sql = query.ToQueryString();
Console.WriteLine(sql);
// Then execute
var results = await query.ToListAsync();
// In Program.cs
builder.Services.AddDbContext<DemoDbContext>(options =>
{
options.UseSqlServer(connectionString);
// Log SQL to console
options.LogTo(Console.WriteLine,
LogLevel.Information);
// Or use this filter
builder.Logging.AddFilter(
"Microsoft.EntityFrameworkCore.Database.Command",
LogLevel.Information);
});
Use SQL Server Profiler or Extended Events to capture all queries hitting your database in real-time.
# Install MiniProfiler
dotnet add package MiniProfiler.AspNetCore.Mvc
dotnet add package MiniProfiler.EntityFrameworkCore
Provides a UI overlay showing all queries, their execution time, and duplicate query detection.