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.
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.
"SQL injection is mixing code and data. If I build
"... WHERE Name = '" + name + "'", whatever is innamebecomes 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'sSqlParameter; in Dapper it's the anonymous object; in EF Core, LINQ is parameterised automatically, andFromSqlorExecuteSqlwith an interpolated string is too, because they take aFormattableStringand turn each hole into aDbParameter.The one I catch in code review is
FromSqlRawwith$"...". It looks identical toFromSql, butFromSqlRawtakes 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 orASC/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 usessp_executesqlwith parameters andQUOTENAMEfor identifiers, neverEXEC(@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."
db.Customers.FromSqlRaw($"SELECT * FROM Customers WHERE Email = '{email}'")email as x' OR 1=1 --, turning the filter into 'every customer'.db.Customers.FromSql($"SELECT * FROM Customers WHERE Email = {email}") or plain LINQ db.Customers.Where(c => c.Email == email).| 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 |
| 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 |
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.
Checks that the candidate knows exactly why parameterisation works, can spot the EF Core FromSqlRaw trap, and handles non-parameterisable identifiers safely.
Green flags
sp_executesql)FromSqlRaw($"...") immediatelyRed flags
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).
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.
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).
-- 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;
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.
SELECT, INSERT, UPDATE, DELETE on needed schemas, EXECUTE on procedures, no DDL.FromSqlRaw($"...") query, log the generated SQL with LogTo, then switch to FromSql and compare.EF1002 as an error in .editorconfig and see the build fail.sp_executesql with parameters.SELECT on one schema and try a DROP TABLE through it.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
$"..." 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.EXEC(@sql) and concatenation are injectable. Instead: use sp_executesql with parameters and QUOTENAME for validated identifiers.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.Replace("'", "''")). Why it is wrong: it misses edge cases (numeric contexts, encodings) and is easy to forget. Instead: parameterise.db_owner or sa. Why it is wrong: one injection becomes full database compromise. Instead: a least-privilege role; migrations under a separate identity.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.
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.
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.
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].
Last updated 23 Nov 2026.