LINQ Interview Question #107

How can you inspect SQL generated from an EF Core LINQ query?

LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced

Quick Interview Answer

EF Core provides ToQueryString for inspecting the SQL representation of an IQueryable without executing the query. Application logging can also capture generated database commands.

Detailed Explanation

EF Core provides ToQueryString for inspecting the SQL representation of an IQueryable without executing the query. Application logging can also capture generated database commands.

Inspecting generated SQL is useful when diagnosing unexpected joins, excessive columns, inefficient predicates, or other performance problems.

Code Example

var query = db.Products
    .Where(p => p.Price > 100)
    .OrderBy(p => p.Name);

string sql = query.ToQueryString();

Console.WriteLine(sql);