Tutorials Entity Framework Core Tutorial
Raw SQL in EF Core
Raw SQL in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 58 of 100
Raw SQL in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~10 min · Module 6: Advanced EF Core
What is this?
Raw SQL executes hand-written T-SQL via FromSqlRaw, ExecuteSqlRaw, or SqlQuery — mapped to entities or scalars when shape matches.
Why should you care?
ShopNest legacy reporting query already tuned by DBA — FromSqlRaw reuses it without rewriting complex LINQ.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
var topProducts = await _context.Products
.FromSqlRaw(@"
SELECT p.Id, p.Name, p.Price, p.CategoryId, p.Sku, p.StockQty, p.IsPublished
FROM Products p
INNER JOIN (
SELECT TOP 10 ProductId, SUM(Quantity) AS Units
FROM OrderItems
GROUP BY ProductId
ORDER BY Units DESC
) s ON p.Id = s.ProductId")
.AsNoTracking()
.ToListAsync();
What happened?
- FromSqlRaw maps result columns to Product properties — must match shape.
- Parameterize with FromSqlInterpolated to prevent injection.
Practice next
- Prefer FromSqlInterpolated for parameters: $"WHERE CategoryId = {id}".
- Ensure selected columns match entity properties or use keyless type.
- Compose LINQ after FromSqlRaw for additional filters.
- Map keyless TopSellerDto with SqlQuery instead of full entity.
- Add AsNoTracking after FromSqlRaw for read reports.
Remember
FromSqlRaw runs custom SELECT mapped to entities. Always parameterize user values. Use for DBA-tuned or legacy SQL.
ShopNest bestseller report
Analytics team ships stored SQL for top sellers; API wraps FromSqlRaw.
Outcome: Report matches SSMS benchmark without fragile LINQ translation.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!