0Pricing
C# Academy · Lesson

Raw SQL, Stored Procedures & Interpolation

Execute raw SQL safely with FromSqlRaw, FromSqlInterpolated, and stored procedures while avoiding injection.

When to Use Raw SQL in EF Core

Most queries work fine with LINQ, but some scenarios need raw SQL: complex analytics, vendor-specific functions, stored procedures, or performance-critical queries that LINQ translates poorly.

EF Core provides safe ways to use raw SQL without sacrificing security.

FromSqlRaw: Safe Parameterized Queries

FromSqlRaw executes raw SQL and maps results back to entities. Always use {0} placeholders — never string concatenation — to prevent SQL injection.

// SAFE: parameterized
var products = await _db.Products
    .FromSqlRaw("SELECT * FROM Products WHERE Price > {0}", 100m)
    .ToListAsync();

// DANGEROUS: never do this
// FromSqlRaw("SELECT * FROM Products WHERE Price > " + price)

All lessons in this course

  1. Eager, Lazy & Explicit Loading
  2. Raw SQL, Stored Procedures & Interpolation
  3. Compiled Queries & Performance
  4. Global Query Filters & Owned Entities
← Back to C# Academy