How do you configure and use raw SQL queries alongside LINQ in EF Core when a complex query is difficult or inefficient to express in LINQ?
Short answer
FromSqlRaw/FromSqlInterpolated let you execute raw SQL that maps results to an entity type (composable with further LINQ operations like Where in some cases), while ExecuteSqlRawAsync/ExecuteSqlInterpolatedAsync execute raw SQL commands (like bulk updates) that don't return…
Advertisement
AModel answer
FromSqlRaw/FromSqlInterpolated let you execute raw SQL that maps results to an entity type (composable with further LINQ operations like Where in some cases), while ExecuteSqlRawAsync/ExecuteSqlInterpolatedAsync execute raw SQL commands (like bulk updates) that don't return entities -- always use the interpolated or parameterized variants (never raw string concatenation) to avoid SQL injection vulnerabilities, reserving raw SQL for genuinely complex queries (recursive CTEs, database-specific functions) that LINQ can't cleanly express.
// Safe: parameterized via string interpolation (EF Core handles parameterization)
var minPrice = 100m;
var products = await context.Products
.FromSqlInterpolated($"SELECT * FROM Products WHERE Price > {minPrice}")
.ToListAsync();
// DANGEROUS: raw concatenation, vulnerable to SQL injection -- never do this
// FromSqlRaw($"SELECT * FROM Products WHERE Price > {minPrice}")Real-world example
A reporting feature requiring a recursive CTE to compute a hierarchical category tree uses FromSqlInterpolated for that specific complex query, while every other simpler query in the application continues using standard LINQ.
Likely follow-ups
- Why is FromSqlInterpolated safe from SQL injection despite looking like string interpolation?
- When does raw SQL genuinely outperform an equivalent LINQ query?
Related topics