EF Core ExecuteSql — Complete Guide
In this tutorial, you'll learn about EF Core ExecuteSql. We cover key concepts, practical examples, and best practices.
You need to execute a bulk update, a stored procedure, or a DDL command that does not return rows. Loading entities into the change tracker and calling SaveChanges is inefficient for bulk operations. ExecuteSql runs commands directly against the database.
Wrong
// Loading all entities to update one column:
var products = await db.Products.Where(p => p.Category == "Old").ToListAsync();
foreach (var p in products)
{
p.Category = "New";
}
await db.SaveChangesAsync();
Output: Loads all matching entities into memory, tracks changes, sends individual UPDATE statements. Inefficient for bulk operations.
Right
await db.Database.ExecuteSqlRawAsync(
"UPDATE Products SET Category = 'New' WHERE Category = 'Old'");
Output: Single SQL UPDATE statement. No entities loaded. No tracking. Maximum performance.
Parameterized version:
await db.Database.ExecuteSqlInterpolatedAsync(
$"UPDATE Products SET Price = Price * {multiplier} WHERE Category = {category}");
For stored procedures:
await db.Database.ExecuteSqlRawAsync(
"EXEC ArchiveOrders @cutoffDate", new SqlParameter("@cutoffDate", cutoff));
Prevention
- Use
ExecuteSqlRaw/ExecuteSqlInterpolatedfor bulk UPDATE, DELETE, and INSERT. - Use
ExecuteSqlfor stored procedure calls that do not return results. - Use
ExecuteSqlfor DDL commands (CREATE, ALTER, DROP). - Always use parameters to prevent SQL injection.
- Use
ExecuteSqlInterpolatedfor safer parameterized syntax. - Combine with transactions for atomic bulk operations.
- Do not use
ExecuteSqlfor queries that return data — useFromSqlorSqlQuery.
Common Mistakes with core execute sql
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
ExecuteSql is used in DodaTech's data maintenance jobs for efficient bulk operations. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro