A strong answer gives a concrete scenario, why EF Core struggled, and why raw SQL was the right trade-off — while explaining that EF remained the default. Example scenario: a monthly sales report "We needed a report with running totals and rankings per region: revenue per salesperson, month-over-month change, and top 3 performers per region, over about 20 million order rows." Why EF Core did not work well - The logic needed window functions (SUM() OVER, LAG(), DENSE_RANK() OVER (PARTITION BY ...)). EF Core's LINQ translation does not express these directly (support has been growing in recent versions, but not for everything we needed). - The LINQ approximation produced nested subqueries that were slow, or required loading data into memory, which was impossible at that volume. - We needed specific query hints and a tuned execution plan for a reporting replica. What we did - Wrote the query in SQL (a stored procedure in one project, or FromSql / SqlQuery<T> in EF Core in another) mapping results to a DTO: var rows = await db.Database.SqlQuery<SalesRankRow>($""" SELECT Region, SalesPerson, Revenue, DENSE_RANK() OVER (PARTITION BY Region ORDER BY Revenue DESC) AS RankInRegion FROM dbo.MonthlySales WHERE Month = {month} """).ToListAsync(ct); The interpolated string is converted to parameters by EF Core, so it is safe from SQL injection. Other common scenarios where raw SQL or stored procedures win - Bulk operations on many rows: before ExecuteUpdate and ExecuteDelete (EF Core 7+), mass updates loaded entities one by one; for very large imports, SqlBulkCopy or table-valued parameters are still much faster. - Complex recursive queries (recursive CTEs for hierarchies). - Database-specific features: full-text search, JSON functions, temporal tables, MERGE upserts, query hints. - Legacy stored procedures that encapsulate business logic owned by a DBA team. - Performance-critical hot paths where hand-tuned SQL or Dapper reduces overhead. How I kept it maintainable - Raw SQL is isolated in repository or query classes, always parameterised, covered by integration tests against the real database engine, and reviewed with execution plans. - EF Core remained the default for CRUD and most queries, because it gives type safety, migrations and change tracking. Interview summary: "EF Core is my default; I use raw SQL when the query needs database features LINQ cannot express efficiently, or for bulk and performance-critical operations — always parameterised and tested."
Ravindra Wadile · · 0 likes