Entity Framework Core Interview Question #136

How can you inspect SQL generated by EF Core?

Performance, Raw SQL, Stored Procedures & Advanced Queries Senior Advanced

Quick Interview Answer

ToQueryString can display the SQL representation of an IQueryable for diagnostics. EF Core logging can also record executed commands and timings. Inspecting generated SQL helps identify unnecessary joins, selected columns, repeated queries, and unexpected query shapes. Production logging should avoid exposing sensitive information.

Detailed Explanation

ToQueryString can display the SQL representation of an IQueryable for diagnostics. EF Core logging can also record executed commands and timings. Inspecting generated SQL helps identify unnecessary joins, selected columns, repeated queries, and unexpected query shapes. Production logging should avoid exposing sensitive information.

Code Example

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

string sql = query.ToQueryString();