📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

When and how do you use raw SQL in EF Core? Compare FromSql, FromSqlRaw and SqlQuery<T>, explain ExecuteSql, show how SQL injection can still happen through string interpolation, and explain when you can compose LINQ on top of a raw query.

Covers EF Core raw SQL APIs (FromSql/FromSqlInterpolated, FromSqlRaw, SqlQuery and SqlQueryRaw, ExecuteSql and ExecuteSqlRaw), how interpolated strings become parameters, the injection traps with FromSqlRaw and dynamic identifiers, the EF1002 analyser, and composing LINQ over composable SQL versus stored procedures.

Mid-Level Security Intermediate ef-core raw-sql security sql-injection sql-server stored-procedures

🎯 Key points

  • FromSql / FromSqlInterpolated take a FormattableString: each {hole} becomes a DbParameter
  • FromSqlRaw takes a plain string: safe only with explicit @p parameters, never concatenation or $"" holes
  • Database.SqlQuery<T> for scalars (EF Core 7) and unmapped types (EF Core 8); SqlQueryRaw is the unsafe-by-default twin
  • Database.ExecuteSql / ExecuteSqlRaw return rows affected and bypass the change tracker, so reload or Clear() tracked entities afterwards
  • Identifiers (table, column, ORDER BY) cannot be parameters: whitelist them, QUOTENAME as a backstop
  • EF1002 analyser (EF Core 8+) flags interpolated strings passed to the Raw methods; make it a build error in CI
  • Composable SELECT: LINQ is wrapped as a subquery; EXEC of a stored procedure is not composable, so materialise first
  • FromSql results map to entities by column name, must return all mapped columns, and are tracked unless AsNoTracking

⏱ 30-second answer

Use raw SQL for what LINQ can't express well: hints, window functions, full-text search, table-valued functions or stored procedures. FromSql($"... {id}") takes a FormattableString, so every interpolation hole becomes a DbParameter; that is the safe default. FromSqlRaw takes a plain string and is safe only with explicit @p parameters: passing $"...{input}" to it concatenates the value into SQL, which is SQL injection (EF Core 8's EF1002 analyser warns about it). SqlQuery<T> returns scalars or unmapped DTOs, and ExecuteSql runs commands. Identifiers such as sort columns can never be parameters, so whitelist them. A composable SELECT can have LINQ added on top (EF wraps it as a subquery), but EXEC cannot. The trade-off is power and performance versus losing compile-time checking, so keep raw SQL small and tested.

🗣 Full answer (senior)

How I would answer this in an interview

"I use raw SQL in EF Core when LINQ either can't express the query or produces a plan I can't live with: a CROSS APPLY to a table-valued function, CONTAINSTABLE full-text search, a query hint, or an existing stored procedure. EF Core gives me three families. FromSql on a DbSet returns entities. Database.SqlQuery<T> returns scalars or, since EF Core 8, any unmapped type. Database.ExecuteSql runs a command and returns rows affected. Each has a Raw twin.

The security point is the type of the argument. FromSql, SqlQuery and ExecuteSql take a FormattableString, so when I write $"SELECT ... WHERE Id = {id}", the compiler keeps the format and the arguments separate and EF turns each hole into @p0, @p1. The Raw methods take a string. If someone writes FromSqlRaw($"... WHERE Name = '{name}'"), the interpolation happens before EF sees it, so the value is concatenated into the SQL text. That's classic injection, and it looks almost identical in a review. EF Core 8 added the EF1002 analyser for exactly this. For example, at [company] I [found an admin search that passed a sort column and filter through FromSqlRaw with string interpolation]; we [fixed it with parameters and a whitelist and added EF1002 as an error], and [the pen test retest came back clean].

The second trap is identifiers. You can't parameterise a table name or an ORDER BY column, so dynamic sorting means mapping the client's value through a whitelist to a known column, never passing it through. On composition: if the SQL is a plain SELECT, EF wraps it as a subquery so I can add Where, OrderBy and Include. A stored procedure call isn't composable, so I call AsAsyncEnumerable() or ToListAsync() straight after it. The mistake I see is treating FromSqlRaw as 'the same thing with more flexibility'. It's the same thing without the seatbelt."


The APIs

API Input type Returns Parameters Composable
DbSet.FromSql($"...") (EF 7+) / FromSqlInterpolated FormattableString Entities (tracked) Automatic Yes, if a SELECT
DbSet.FromSqlRaw("... @p0", p) string + object[] Entities Manual Yes, if a SELECT
Database.SqlQuery<T>($"...") FormattableString Scalars, unmapped types (EF 8+) Automatic Yes (scalar column must be named Value)
Database.SqlQueryRaw<T>(...) string Same Manual Yes
Database.ExecuteSql($"...") FormattableString int rows affected Automatic n/a
Database.ExecuteSqlRaw(...) string int Manual n/a

Safe vs unsafe

Code Safe?
FromSql($"... WHERE Name = {name}") Yes: @p0
FromSqlRaw("... WHERE Name = {0}", name) Yes: {0} becomes a parameter
FromSqlRaw("... WHERE Name = @name", new SqlParameter("@name", name)) Yes
FromSqlRaw($"... WHERE Name = '{name}'") No: concatenated
FromSqlRaw("... ORDER BY " + sortColumn) No: identifier injection
var sql = $"... {name}"; FromSqlRaw(sql) No

Production example

Moving a product search from LINQ Contains (a full scan on [1.8M] rows, p95 [1.9 s]) to FromSql with CONTAINSTABLE on a full-text index, then composing .Where(p => p.IsActive).Take(50) on top, brought p95 to [120 ms] while keeping every input parameterised.

🔍 What the interviewer is checking

Checks that the candidate can use raw SQL in EF Core without introducing SQL injection, and understands composition and mapping rules.

Green flags

  • Explains FormattableString vs string overloads and why FromSqlRaw($"") is unsafe.
  • Knows identifiers need a whitelist.
  • Knows composable SELECT vs non-composable EXEC.
  • Mentions the EF1002 analyser, tests against real SQL Server, least privilege.

Red flags

  • Believes any $"" string is parameterised.
  • Escapes quotes by hand instead of parameterising.
  • Passes sort columns straight from the query string.

📚 Learn in depth

1. How FormattableString parameterisation works

$"SELECT * FROM Products WHERE Name = {name} AND Price < {max}"

  target type FormattableString  ->  Format = "... Name = {0} AND Price < {1}"
                                      Args   = [name, max]
  target type string             ->  "... Name = Widget AND Price < 10"   (already concatenated)

EF Core's FromSql replaces {0}, {1} with @p0, @p1 and adds SqlParameters. The plan is cached once per shape, which also helps performance. Overload resolution is the whole story: the same $"" literal is safe or unsafe depending on the parameter type of the method it is passed to.

2. Composition

var q = db.Products
    .FromSql($"SELECT * FROM Products WITH (FORCESEEK) WHERE CategoryId = {cat}")
    .Where(p => p.Price < max)
    .OrderBy(p => p.Name);
SELECT [p].[Id], [p].[Name], [p].[Price], [p].[CategoryId]
FROM (
    SELECT * FROM Products WITH (FORCESEEK) WHERE CategoryId = @p0
) AS [p]
WHERE [p].[Price] < @__max_1
ORDER BY [p].[Name]

Rules: the SQL must be valid as a subquery (no trailing ;, no ORDER BY without TOP), and it must return every column the entity maps, with matching names. EXEC dbo.GetProducts @p0 can't be a subquery, so composing on it throws; call .AsAsyncEnumerable() and filter in memory, or wrap the logic in an inline table-valued function, which is composable and can be mapped with HasDbFunction.

3. SqlQuery for non-entities

var ids = await db.Database
    .SqlQuery<int>($"SELECT Id AS Value FROM dbo.Orders WHERE Status = {status}")
    .Where(v => v > lastId)   // composes because the column is named Value
    .ToListAsync(ct);

var rows = await db.Database
    .SqlQuery<SalesRow>($"SELECT Region, SUM(Total) AS Total FROM dbo.Orders GROUP BY Region")
    .ToListAsync(ct);         // EF Core 8+: unmapped record type

4. Identifiers

Parameters carry values, not SQL syntax. ORDER BY @col sorts by a constant. Dynamic identifiers need a whitelist (switch to a known column name or, better, to a LINQ OrderBy expression). QUOTENAME in T-SQL is a backstop, not a design.

5. Stored procedures and output parameters

var total = new SqlParameter("@total", SqlDbType.Decimal) { Direction = ParameterDirection.Output, Precision = 18, Scale = 2 };
await db.Database.ExecuteSqlRawAsync("EXEC dbo.CloseMonth @month, @total OUTPUT",
    [new SqlParameter("@month", month), total], ct);

6. Tracking and the change tracker

FromSql results are tracked like any query unless you add AsNoTracking(). ExecuteSql bypasses the tracker: entities already loaded keep stale values, so reload or ChangeTracker.Clear() afterwards if you keep using the context.

Try it yourself

  1. Write FromSqlRaw($"... '{name}'") and FromSql($"... {name}"), pass x' OR 1=1 --, and compare the SQL in LogTo output.
  2. Turn on <WarningsAsErrors>EF1002</WarningsAsErrors> and see the build fail on the unsafe version.
  3. Compose .Where().OrderBy() on a FromSql and read the generated subquery with ToQueryString().
  4. Try composing on EXEC and read the exception; rewrite as an inline TVF.
  5. Map a SqlQuery<MonthlyTotal> record and compare its plan to the equivalent LINQ GroupBy.

💻 Code

Safe raw SQL: entities, unmapped DTOs, commands and a whitelisted sort.

namespace Catalogue.Search;

using Microsoft.EntityFrameworkCore;

public sealed record SearchHit(int Id, string Name, int Rank);

public sealed class ProductSearch(CatalogueDbContext db)
{
    // FromSql: {term} and {take} become @p0, @p1. Composable, so LINQ is added on top.
    public Task<List<Product>> SearchAsync(string term, int categoryId, CancellationToken ct) =>
        db.Products
          .FromSql($"""
              SELECT p.* FROM dbo.Products p
              JOIN CONTAINSTABLE(dbo.Products, Name, {term}) ft ON ft.[KEY] = p.Id
              """)
          .Where(p => p.CategoryId == categoryId && p.IsActive)
          .AsNoTracking()
          .Take(50)
          .ToListAsync(ct);

    // SqlQuery<T>: unmapped record (EF Core 8+).
    public Task<List<SearchHit>> RankedAsync(string term, CancellationToken ct) =>
        db.Database.SqlQuery<SearchHit>($"""
              SELECT p.Id, p.Name, ft.[RANK] AS [Rank]
              FROM dbo.Products p JOIN CONTAINSTABLE(dbo.Products, Name, {term}) ft ON ft.[KEY] = p.Id
              """).ToListAsync(ct);

    // ExecuteSql: a command, parameterised, bypasses the change tracker.
    public Task<int> ArchiveAsync(DateOnly before, CancellationToken ct) =>
        db.Database.ExecuteSqlAsync($"UPDATE dbo.Products SET IsActive = 0 WHERE DiscontinuedOn < {before}", ct);

    // Identifiers cannot be parameters: whitelist to an expression, never pass the string through.
    public static IQueryable<Product> Sort(IQueryable<Product> q, string? sort) => sort switch
    {
        "name"  => q.OrderBy(p => p.Name),
        "price" => q.OrderBy(p => p.Price),
        _       => q.OrderBy(p => p.Id)
    };
}
// UNSAFE - the interpolation runs before EF sees the string. EF1002 warns.
// db.Products.FromSqlRaw($"SELECT * FROM dbo.Products WHERE Name = '{name}' ORDER BY {sort}");
<!-- Directory.Build.props: make the analyser a build break -->
<PropertyGroup>
  <WarningsAsErrors>$(WarningsAsErrors);EF1002</WarningsAsErrors>
</PropertyGroup>

⚠ Common mistakes

  • Mistake: Passing an interpolated string to FromSqlRaw or ExecuteSqlRaw. Why it is wrong: the values are concatenated into the SQL text, which is SQL injection. Instead: use FromSql / ExecuteSql with $"", or Raw with explicit parameters.
  • Mistake: Building the SQL in a string variable first and passing it to FromSql. Why it is wrong: it either won't compile or, via FromSqlRaw, loses parameterisation. Instead: keep it a FormattableString or use SqlParameters.
  • Mistake: Passing a client-supplied sort column or table name into the SQL. Why it is wrong: identifiers can't be parameters, so this is injection. Instead: whitelist to known columns or LINQ OrderBy.
  • Mistake: Composing LINQ on an EXEC stored procedure. Why it is wrong: EF wraps the SQL as a subquery, which EXEC can't be, so it throws. Instead: materialise with AsAsyncEnumerable() first, or use an inline TVF.
  • Mistake: SELECT only some columns into an entity with FromSql. Why it is wrong: EF requires every mapped column, so it throws at runtime. Instead: return all columns or use SqlQuery<TDto>.
  • Mistake: Using ExecuteSql and then continuing with tracked entities. Why it is wrong: the tracker doesn't know the rows changed, so later saves can overwrite them. Instead: ChangeTracker.Clear() or reload.
  • Mistake: Adding ; or ORDER BY without TOP in composable SQL. Why it is wrong: the subquery becomes invalid. Instead: leave ordering to LINQ.

🏛 Senior insight: trade-offs

Raw SQL in EF Core is a scalpel. I allow it where it earns its keep (full-text, TVFs, hints, existing procedures, reports) and keep it behind a small, tested class, never scattered through handlers. Every raw query gets an integration test against a real SQL Server (Testcontainers) because the compiler can't check it, and a column rename otherwise breaks it at runtime. I make EF1002 a build error and ban Raw methods outside an allow-listed folder through code review or a Roslyn banned-API analyser.

The security reasoning goes beyond injection: parameterised queries also give plan reuse, and the OWASP and ACSC guidance both treat parameterisation as the primary control. Least privilege on the database login (no db_owner for the app) limits the blast radius if something slips through.

Option When it fits Cost When not to
LINQ Most queries Translation limits Hints, full-text, TVFs
FromSql Entity results needing SQL features No compile-time checking Simple filters LINQ handles
SqlQuery<T> Reports, scalars, DTOs Same When you need tracked entities
ExecuteSql Commands, procedures Bypasses tracker and interceptors on SaveChanges When domain logic must run
Dapper on the same connection Large hand-tuned read models Second library A handful of queries

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions dynamic sorting or filtering. Why: Checks safe dynamic querying without raw SQL.
    How to answer

    Start from db.Products.AsNoTracking() as an IQueryable<T> and add Where clauses conditionally; each one ANDs into the same SQL WHERE. For OR logic, combine Expression<Func<T,bool>> predicates by rebinding their parameters (or use LinqKit), never Func<T,bool>, which would force in-memory evaluation.

    For sorting, map the client's string to a whitelisted dictionary of key-selector expressions and always add ThenBy(x => x.Id) so paging is stable. Cap the page size on the server. Values captured in closures become SQL parameters, so there's no injection risk and plans are reused.

    The trade-off: flexible search is easy to compose, but every optional filter combination is a different SQL shape, so index for the common ones and test the translation.

  2. When: Candidate says LINQ couldn't express a query. Why: Checks when LINQ translation is enough before reaching for raw SQL.
    How to answer

    EF Core takes the expression tree built by IQueryable operators, normalises it, translates it into a SQL expression tree using the provider's method translators (so SQL Server, PostgreSQL and SQLite produce different SQL and support different methods), and generates SQL text. The compiled result is cached by query shape, and captured variables become parameters.

    • It translates mapped properties, navigations, operators, aggregates, GroupBy, and known methods such as string.Contains, StartsWith, DateTime parts and EF.Functions.Like.
    • From EF Core 3.0 onwards (still true in EF Core 10), client evaluation is allowed only in the final Select. Anything untranslatable elsewhere throws an InvalidOperationException instead of silently loading the table.
    • I check the output with ToQueryString() or LogTo.

    The trade-off: LINQ is expressive, but you must know which C# your provider can turn into SQL.

  3. When: Candidate mentions stored procedures not being composable. Why: Checks the composable alternative to stored procedures.
    How to answer

    Create an inline table-valued function in SQL Server, add a method on the DbContext that returns IQueryable<T> via FromExpression(() => Fn(arg)), and register it with modelBuilder.HasDbFunction (supported since EF Core 5). EF Core then translates db.Fn(x).Where(...).Include(...) into SELECT ... FROM dbo.Fn(@p0) WHERE .... Inline TVFs are a single SELECT, so the optimiser expands them into the outer query like a parameterised view and uses real statistics. Multi-statement TVFs allow procedural logic (table variables, loops, several statements) when you genuinely need it, but they're opaque to the optimiser: SQL Server 2017+ interleaved execution helps, yet their row estimates are often poor, so they're usually slower when composed with large queries.

🛠 Real-world problems: how you handle them

SQL injection in an admin search built with FromSqlRaw interpolation
Situation
An internal [case-management] admin portal on ASP.NET Core and Azure SQL (Australia East) holding [~300k] client records with personal information covered by the Privacy Act. A search endpoint built `FromSqlRaw($"... WHERE Surname LIKE '%{term}%' ORDER BY {sort}")`.
Signals
An external pen test reported a boolean-based SQL injection on `term` and an error-based one on `sort`; Azure SQL auditing showed queries with `OR 1=1` from the tester's IP; Defender for SQL raised a 'Potential SQL injection' alert.
Investigation
Reproduced locally with `LogTo` and saw the payload inside the SQL text, not as `@p0`. Searched the solution for `FromSqlRaw(`, `ExecuteSqlRaw(` and `SqlQueryRaw(` with `$"` arguments, finding [4] more. Checked the app's database login: it had `db_owner`, so injection could have read every table. Reviewed audit logs for the past [90] days for similar patterns to decide whether a Notifiable Data Breaches assessment was needed.
Resolution
Immediately: hot-fixed the endpoint to `FromSql` with parameters and a whitelist `switch` for `sort`, deployed within [hours]. Then: replaced the other raw calls, moved the full-text part to `CONTAINSTABLE` with a parameter, and reduced the app login to `db_datareader`/`db_datawriter` plus `EXECUTE` on specific procedures.
Prevention
EF1002 as a build error; a banned-API analyser rule allowing `*Raw` methods only in one reviewed folder; integration tests that send injection payloads and assert the result count; Defender for SQL alerts routed to on-call; least-privilege logins documented in an ADR.

How to tell it (STAR)

**S:** At [company], a pen test of our [case-management] admin portal found SQL injection in the search endpoint, on a database with [~300k] clients' personal information. **T:** I owned the fix and the assessment of whether anything had been exposed. **A:** I reproduced it and saw the search used `FromSqlRaw` with string interpolation, so the term and the sort column went straight into the SQL. I hot-fixed it the same day with `FromSql` and a whitelist for sorting, then found [four] similar calls and fixed those, reduced the app's database login from `db_owner` to read/write only, reviewed [90] days of audit logs with our privacy officer, and made the EF1002 analyser a build error. **R:** The retest came back clean, the logs showed [no exploitation beyond the tester], and the build has blocked [N] unsafe raw SQL calls since.

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me