From SQL to Entity Framework
When to Drop to Raw SQL
LINQ Until It Fights You
LINQ is the right default for everyday reads and writes. The compiler checks it, and it survives renames. Drop to SQL when:
- The SQL is already written and proven. Don't translate a report you trust just to have it in C#.
- LINQ can't say it clearly. If it takes you five minutes to read and the SQL takes one, use the SQL.
- You need something SQL Server specific, like a query hint or an unusual window function.
- You're changing a lot of rows. More on that below.
"EF is slow" isn't on the list. Look at ToQueryString() first. Usually it's the query.
Any Result Shape
SqlQuery runs your SQL and fills any class whose properties match the column names:
var rows = await db.Database
.SqlQuery<RegionRevenue>($"""
SELECT c.Region,
COUNT(DISTINCT o.OrderId) AS Orders,
SUM(l.Quantity * l.UnitPrice) AS Revenue
FROM dbo.Orders AS o
JOIN dbo.Customers AS c ON c.CustomerId = o.CustomerId
JOIN dbo.OrderLines AS l ON l.OrderId = o.OrderId
WHERE o.Status = 'Shipped'
AND o.OrderDate >= {from} AND o.OrderDate < {to}
GROUP BY c.Region
""")
.ToListAsync();
{from} and {to} look like they get pasted into the text. They don't. EF turns them into parameters, @p0 and @p1, so it's safe.
The One-Word Security Hole
// SAFE: becomes a parameter
db.Orders.FromSql(
$"SELECT * FROM dbo.Orders WHERE Status = {status}");
// DANGEROUS: pasted straight into the SQL
db.Orders.FromSqlRaw(
$"SELECT * FROM dbo.Orders WHERE Status = '{status}'");
Three letters apart. The second is SQL injection: if status came from a user, they can run their own SQL in your database. EF warns about it at build time (warning EF1002). Never ignore that one. When you review AI code, search for Raw( and check every hit.
Changing Many Rows
The slow way loads every row, changes it in C#, and saves. You don't need raw SQL to skip that:
var cutoff = new DateTime(2023, 1, 1);
int changed = await db.Orders
.Where(o => o.Status == "Open" && o.OrderDate < cutoff)
.ExecuteUpdateAsync(s =>
s.SetProperty(o => o.Status, "Cancelled"));
That's one UPDATE statement. In a test database it changed 10,013 rows without loading a single one. It runs right away, doesn't wait for SaveChanges, and doesn't refresh objects you already loaded. changed is your row count, so check it, the same as Module 2.
Porting a stored procedure or report to LINQ? Keep the SQL as the answer key. Have the AI write a test that runs both against the same data and fails on any difference. If nobody can make them match, keep the SQL.
Which call is open to SQL injection when status comes from a user?