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

📚 Interview question

How does SQL injection happen in a .NET application, and how do you prevent it in ADO.NET, Dapper and EF Core? Show the vulnerable and fixed code, explain why FromSqlRaw with string interpolation is dangerous, and how you handle things that can't be parameterised, such as a dynamic ORDER BY column.

SQL injection across ADO.NET, Dapper, EF Core and stored procedures: parameterisation, FromSql vs FromSqlRaw, identifiers that can't be parameters, dynamic SQL with sp_executesql, and least privilege.

Intermediate Security Intermediate ado-net dapper ef-core security sql-injection sql-server

🎯 Key points

  • Injection = untrusted data concatenated into SQL text and parsed as code
  • Parameters send values separately from the SQL text: SqlParameter, Dapper anonymous objects
  • EF Core FromSql/ExecuteSql with interpolation creates DbParameters; FromSqlRaw with $"" interpolation does not
  • Identifiers (column, table, sort direction) can't be parameters: map from an allow-list
  • Stored procedures are only safe if they don't build dynamic SQL with EXEC(@sql); use sp_executesql and QUOTENAME
  • Second-order injection: data stored safely, later concatenated
  • Least-privilege database login limits the blast radius
  • Parameterisation also improves plan cache reuse

⏱ 30-second answer

SQL injection happens when untrusted input is concatenated into SQL text, so the database parses part of the data as code. The fix is parameterisation: the SQL text is fixed and values travel separately as typed parameters (SqlParameter in ADO.NET, an anonymous object in Dapper, LINQ or FromSql($"...") in EF Core).

In EF Core 7 and later, FromSql, ExecuteSql and SqlQuery<T> take a FormattableString and turn every interpolation hole into a DbParameter; they are the current names for the older FromSqlInterpolated/ExecuteSqlInterpolated. The trap is FromSqlRaw($"... {input}") or ExecuteSqlRaw: they take a plain string, so interpolation happens before EF sees it and it's concatenation. Things that can't be parameters (column names, sort direction) must come from an allow-list. Stored procedures aren't automatically safe if they build dynamic SQL. Add a least-privilege login so a bug can't drop tables.

🗣 Full answer (senior)

How I would answer this in an interview

"SQL injection is mixing code and data. If I build "... WHERE Name = '" + name + "'", whatever is in name becomes part of the SQL the server parses, and a quote is all it takes to change the query. The fix is to never put data in SQL text: send parameters. In ADO.NET that's SqlParameter; in Dapper it's the anonymous object; in EF Core, LINQ is parameterised automatically, and FromSql or ExecuteSql with an interpolated string is too, because they take a FormattableString and turn each hole into a DbParameter.

The one I catch in code review is FromSqlRaw with $"...". It looks identical to FromSql, but FromSqlRaw takes a plain string, so the interpolation has already happened and it's concatenation. The analyser warns about it, and I want that warning as an error. The other gap is anything that isn't a value: you can't parameterise a column name or ASC/DESC. For a client-chosen sort I map an allow-listed field name to an expression or a fixed column. I don't pass the string through. Same in T-SQL: if a procedure builds dynamic SQL, it uses sp_executesql with parameters and QUOTENAME for identifiers, never EXEC(@sql) with concatenation.

Then defence in depth: the app's database login has only the permissions it needs, not db_owner, so even a missed injection can't drop tables or read other schemas. The mistake I see is 'we use stored procedures, so we're safe'. Procedures that concatenate are just as injectable. Parameterise values, allow-list identifiers, and limit the login."


Vulnerable, exploit, fixed

  • Vulnerable: db.Customers.FromSqlRaw($"SELECT * FROM Customers WHERE Email = '{email}'")
  • Exploit (one line): the attacker sends email as x' OR 1=1 --, turning the filter into 'every customer'.
  • Fixed: db.Customers.FromSql($"SELECT * FROM Customers WHERE Email = {email}") or plain LINQ db.Customers.Where(c => c.Email == email).

Safe and unsafe APIs

API Safe with user values? Note
LINQ (Where, Select) Yes Values become parameters
FromSql($"...{v}"), ExecuteSql($"..."), SqlQuery<T>($"...") Yes FormattableString -> DbParameter
FromSqlInterpolated, ExecuteSqlInterpolated Yes Older names, same behaviour
FromSqlRaw("... {0}", v) Yes Positional placeholders become parameters
FromSqlRaw($"...{v}") No String interpolated before EF sees it
Dapper Query<T>(sql, new { v }) Yes @v in SQL
SqlCommand with Parameters.Add Yes Specify SqlDbType and size
SqlCommand with concatenation No Classic injection

What can't be parameterised

Thing Approach
ORDER BY column Allow-list map from API field to column/expression
Sort direction Enum (Asc/Desc), never a string into SQL
Table or schema name Fixed set; QUOTENAME in T-SQL if truly dynamic
IN (...) lists EF Core translates Contains; Dapper expands lists; or a TVP
LIKE patterns Parameter, and escape %, _, [ in the value if users shouldn't use wildcards

Production example

In one codebase, enabling the EF Core analyser and grepping for FromSqlRaw(, ExecuteSqlRaw( and new SqlCommand( found 23 call sites; 3 interpolated request data into raw SQL, one in a reporting endpoint that ran as db_owner. Fixing those took a day; reducing the login to a custom role with SELECT/EXECUTE on two schemas took another, and Query Store showed the plan cache shrink as ad-hoc literal plans were replaced by parameterised ones.

🔍 What the interviewer is checking

Checks that the candidate knows exactly why parameterisation works, can spot the EF Core FromSqlRaw trap, and handles non-parameterisable identifiers safely.

Green flags

  • Explains values travelling separately from SQL text (sp_executesql)
  • Spots FromSqlRaw($"...") immediately
  • Uses an allow-list for sort columns and directions
  • Mentions least privilege and second-order injection

Red flags

  • 'Stored procedures prevent SQL injection'
  • Escapes quotes manually
  • Thinks an ORM makes injection impossible

📚 Learn in depth

1. Why parameters work

Concatenation:   client builds text  "SELECT ... WHERE Email = 'x' OR 1=1 --'"
                 server parses the whole thing -> data became code

Parameterised:   client sends  text:   "SELECT ... WHERE Email = @email"
                               params: @email = N'x'' OR 1=1 --'   (typed value)
                 server parses the text once; @email is only ever a value

On SQL Server, a parameterised SqlCommand becomes an RPC call to sp_executesql with the statement and a parameter list. The value is never parsed as T-SQL. That's also why parameterised queries share cached plans while literal queries create one plan per distinct value (plan cache bloat, and why 'optimise for ad hoc workloads' exists).

2. EF Core's two families

FromSql, ExecuteSql and SqlQuery<T> take a FormattableString. The C# compiler keeps the format and the arguments separate, and EF Core creates a DbParameter per argument. FromSqlRaw and ExecuteSqlRaw take string (plus optional params object[]); a $"..." passed to them is converted to a string by the compiler first. EF Core ships analyser EF1002 which warns on interpolated strings passed to raw methods; treat it as an error.

3. Dapper and ADO.NET details

Dapper maps properties of the parameter object to @name placeholders and expands IEnumerable parameters for IN @ids. In ADO.NET, prefer Parameters.Add("@email", SqlDbType.NVarChar, 256).Value = email over AddWithValue, which infers types (an nvarchar(4000) for a varchar column can cause implicit conversions and scans).

4. Dynamic SQL in T-SQL

-- VULNERABLE
SET @sql = N'SELECT * FROM dbo.Orders ORDER BY ' + @SortColumn;
EXEC (@sql);

-- SAFER: identifier validated and quoted, values parameterised
IF @SortColumn NOT IN (N'OrderDate', N'Total') THROW 50000, 'Invalid sort', 1;
SET @sql = N'SELECT Id, OrderDate, Total FROM dbo.Orders WHERE CustomerId = @cid ORDER BY '
         + QUOTENAME(@SortColumn) + N';';
EXEC sys.sp_executesql @sql, N'@cid int', @cid = @CustomerId;

5. Second-order injection

A value is stored safely with parameters, then later read and concatenated into SQL by another process (a nightly report, an admin search). The rule 'parameterise every query' covers it; 'validate input at the edge' does not.

6. Limiting the blast radius

  • A dedicated login or managed identity user per app with a custom role: SELECT, INSERT, UPDATE, DELETE on needed schemas, EXECUTE on procedures, no DDL.
  • Migrations run under a separate, more privileged identity in the pipeline.
  • Generic error messages to clients so attackers can't use error-based extraction.

Try it yourself

  1. Write the vulnerable FromSqlRaw($"...") query, log the generated SQL with LogTo, then switch to FromSql and compare.
  2. Turn on EF1002 as an error in .editorconfig and see the build fail.
  3. Capture the RPC call in Extended Events or SQL Profiler to see sp_executesql with parameters.
  4. Build a sort allow-list and write a test that an unknown field returns 400.
  5. Create a login with only SELECT on one schema and try a DROP TABLE through it.

💻 Code

Vulnerable and fixed versions in EF Core, Dapper and ADO.NET, plus an allow-listed dynamic sort.

using System.Linq.Expressions;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace Shop.Customers;

public sealed record Customer(int Id, string Email, string Name, DateTime CreatedUtc);

public sealed class CustomerQueries(ShopDb db, SqlConnection connection)
{
    // VULNERABLE: FromSqlRaw receives an already-interpolated string
    public Task<List<Customer>> FindUnsafe(string email, CancellationToken ct) =>
        db.Customers.FromSqlRaw($"SELECT * FROM Customers WHERE Email = '{email}'").ToListAsync(ct);

    // FIXED (EF Core): FormattableString -> DbParameter
    public Task<List<Customer>> Find(string email, CancellationToken ct) =>
        db.Customers.FromSql($"SELECT * FROM Customers WHERE Email = {email}").ToListAsync(ct);

    // FIXED (Dapper)
    public async Task<IReadOnlyList<Customer>> FindDapper(string email, CancellationToken ct) =>
        (await connection.QueryAsync<Customer>(new CommandDefinition(
            "SELECT Id, Email, Name, CreatedUtc FROM Customers WHERE Email = @email",
            new { email }, cancellationToken: ct))).AsList();

    // FIXED (ADO.NET): explicit type and size avoid implicit conversions
    public async Task<int> CountByEmail(string email, CancellationToken ct)
    {
        await using var cmd = new SqlCommand("SELECT COUNT(*) FROM Customers WHERE Email = @email", connection);
        cmd.Parameters.Add("@email", System.Data.SqlDbType.NVarChar, 256).Value = email;
        return (int)(await cmd.ExecuteScalarAsync(ct))!;
    }

    // Identifiers can't be parameters: allow-list maps API names to expressions
    private static readonly Dictionary<string, Expression<Func<Customer, object>>> SortFields =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["name"] = c => c.Name,
            ["created"] = c => c.CreatedUtc,
        };

    public Task<List<Customer>> List(string sort, bool descending, CancellationToken ct)
    {
        if (!SortFields.TryGetValue(sort, out var key))
            throw new ArgumentException($"Unsupported sort field '{sort}'.", nameof(sort));

        var query = db.Customers.AsNoTracking();
        query = descending ? query.OrderByDescending(key) : query.OrderBy(key);
        return query.Take(100).ToListAsync(ct);
    }
}
# .editorconfig: interpolated strings passed to FromSqlRaw/ExecuteSqlRaw fail the build
dotnet_diagnostic.EF1002.severity = error

⚠ Common mistakes

  • Mistake: Passing $"..." to FromSqlRaw or ExecuteSqlRaw. Why it is wrong: the string is interpolated before EF Core sees it, so values are concatenated. Instead: use FromSql/ExecuteSql, or placeholders with arguments; make EF1002 an error.
  • Mistake: Believing stored procedures are always safe. Why it is wrong: procedures that build SQL with EXEC(@sql) and concatenation are injectable. Instead: use sp_executesql with parameters and QUOTENAME for validated identifiers.
  • Mistake: Passing the request's sort field straight into ORDER BY. Why it is wrong: identifiers can't be parameters, so it's concatenation. Instead: map from an allow-list to an expression or column.
  • Mistake: Escaping quotes by hand (Replace("'", "''")). Why it is wrong: it misses edge cases (numeric contexts, encodings) and is easy to forget. Instead: parameterise.
  • Mistake: Validating input at the API edge and calling it done. Why it is wrong: second-order injection uses data that was stored safely. Instead: parameterise every query, everywhere.
  • Mistake: Running the app as db_owner or sa. Why it is wrong: one injection becomes full database compromise. Instead: a least-privilege role; migrations under a separate identity.
  • Mistake: Returning SQL error messages to clients. Why it is wrong: it enables error-based extraction and leaks schema. Instead: ProblemDetails with a generic message; full detail in logs.

🏛 Senior insight: trade-offs

Senior engineers treat SQL injection as solved by construction, then verified. In .NET the safe path is the easy path; the risk is the escape hatches, so make them visible: analysers as errors, a grep in CI for FromSqlRaw, ExecuteSqlRaw, new SqlCommand( and string-built SQL, and review rules for dynamic identifiers. Then assume one slips through and limit the damage with database permissions.

Approach When it fits Cost When not to
LINQ / EF Core Most CRUD and queries None Very complex reporting SQL
FromSql/Dapper with parameters Hand-tuned SQL Review discipline Never 'not' — always parameterise
Dynamic SQL with sp_executesql + QUOTENAME Truly dynamic identifiers in T-SQL Complexity, testing When an allow-list in C# would do
Least-privilege login Every production app Initial role design —
WAF SQLi rules (Front Door, App Gateway) Extra layer False positives, cost As the only control

Measure: count of raw-SQL call sites over time, analyser warnings at zero, and a DAST (ZAP) scan with SQLi rules in the pipeline.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions FromSql, FromSqlRaw or SqlQuery Why: Checks deeper knowledge of EF Core raw SQL, composition on raw queries and ExecuteSql
    How to 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.

  2. When: Candidate mentions allow-listing sort fields Why: Checks they can design safe filtering, sorting and search on a collection endpoint
    How to answer

    I model filters as typed, explicit parameters (status, createdFrom, customerId) bound with [AsParameters], so only filters I've designed and indexed exist. Sorting uses an allow-list: a dictionary from public names like createdAt to EF Core expressions, with -createdAt for descending; anything else is a 400 ValidationProblem. Values only ever reach SQL as parameters through LINQ, never string concatenation.

    For search I use a prefix LIKE for short fields, and SQL Server full-text or Azure AI Search for real text search, because LIKE '%term%' scans the table.

    OData gives you $filter, $orderby and $select for free, but it exposes your model and lets clients write queries you never indexed. The trade-off is flexibility versus predictable cost and a stable contract.

🛠 Real-world problems: how you handle them

Injectable reporting endpoint found by FromSqlRaw interpolation
Situation
An internal reporting API on ASP.NET Core and Azure SQL serves [number] staff. A developer added a 'filter by region' parameter to a hand-written report query under deadline pressure. The app's database user is [db_owner].
Signals
A routine code scan (or ZAP active scan in staging) reports SQL injection on GET /reports/sales?region=; Query Store shows unusual ad-hoc queries with `OR 1=1`-style predicates from the staging pen test; analyser warning EF1002 had been suppressed.
Investigation
Read the handler: `FromSqlRaw($"... WHERE Region = '{region}'")`. Grepped for `FromSqlRaw(`, `ExecuteSqlRaw(` and `new SqlCommand(` across the solution and found [number] call sites, [3] using request data. Checked production Query Store and Azure SQL auditing for suspicious statements to assess exploitation, and reviewed the login's permissions.
Resolution
Immediate: hotfix switching the query to `FromSql` with parameters and deploying within [hours]; confirmed with ZAP. Long term: fixed the other call sites, removed the EF1002 suppression and made it an error, and replaced db_owner with a custom role granting SELECT on reporting views only; migrations moved to a separate pipeline identity.
Prevention
EF1002 as an error, a CI grep for raw SQL APIs requiring reviewer sign-off, ZAP active scan in staging, Azure SQL auditing with alerts on DDL from the app identity, and a secure-coding checklist item on dynamic identifiers.

How to tell it (STAR)

**S:** At [company] a scan found SQL injection in a reporting endpoint: a region filter had been added with `FromSqlRaw` and string interpolation, and the app ran as db_owner. **T:** I had to fix it fast and find out whether it was the only one. **A:** I hotfixed it to `FromSql` the same day, checked Query Store and SQL auditing to confirm it hadn't been exploited in production, then searched every raw SQL call site and fixed [3] more. I made the analyser warning an error and cut the login down to read-only access on reporting views. **R:** No more SQLi findings in the next [two] pen tests, and the blast radius of any future bug dropped from 'whole database' to [two views].

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me