Prevent SQL Injection in .NET with EF Core, Dapper and ADO.NET
Prevent SQL injection in .NET: parameterized queries in ADO.NET, EF Core FromSql, Dapper and stored procedures, plus safe dynamic ORDER BY allowlists.
By Victor Sanchez
SQL injection in .NET is still one of the most common findings we fix, and it almost always has the same cause: a query built by gluing strings together. On a legacy desktop app we remediated, most injection findings came from a few helpers that concatenated user input into SELECT statements. Today we see the same pattern in a .NET 8 API, hidden inside FromSqlRaw calls and stored procedures that build dynamic SQL.
Why does string concatenation lead to SQL injection?
When you concatenate a value into SQL, the database cannot tell your code apart from the user's data. A search box that receives ' OR 1=1 -- turns this:
var sql = "SELECT * FROM Accounts WHERE Owner = '" + owner + "'";
into a query that returns every account. With stacked queries, an attacker can do worse. A parameter fixes this at the protocol level: the SQL text and the value travel separately, and the value is never parsed as SQL. Escaping quotes by hand is not a fix; it breaks on edge cases, encodings and numeric contexts.
How to write parameterized queries in ADO.NET
// Vulnerable
var cmd = new SqlCommand(
"SELECT Id, Balance FROM Accounts WHERE Owner = '" + owner + "'", conn);
// Fixed: explicit type and size, no AddWithValue
var cmd = new SqlCommand(
"SELECT Id, Balance FROM Accounts WHERE Owner = @owner", conn);
cmd.Parameters.Add("@owner", SqlDbType.NVarChar, 100).Value = owner;
Prefer Parameters.Add with an explicit SqlDbType over AddWithValue. AddWithValue infers the type from the .NET value, so a C# string becomes nvarchar. Against a varchar column, that can force an implicit conversion and turn an index seek into a scan.
How to prevent SQL injection in EF Core
LINQ queries are parameterized by default. The risk appears when you drop down to raw SQL. As of EF Core 7 and later, the API looks like this:
| Method | Parameterized? | Use it for |
|---|---|---|
FromSql($"...") | Yes, interpolated values become DbParameters | Default choice for raw SQL |
FromSqlInterpolated($"...") | Yes, same behavior | Older code bases (before EF Core 7) |
FromSqlRaw("...", params) | Only the values you pass as parameters | Truly dynamic SQL, with care |
SqlQuery, ExecuteSql | Yes | Scalars, unmapped types, commands |
// Vulnerable: interpolation inside FromSqlRaw is plain string concatenation
var rows = await db.Accounts
.FromSqlRaw($"SELECT * FROM Accounts WHERE Owner = '{owner}'")
.ToListAsync();
// Fixed: FromSql turns {owner} into @p0
var rows = await db.Accounts
.FromSql($"SELECT * FROM Accounts WHERE Owner = {owner}")
.ToListAsync();
// Also fine: FromSqlRaw with an explicit parameter
var rows = await db.Accounts
.FromSqlRaw("SELECT * FROM Accounts WHERE Owner = @owner",
new SqlParameter("@owner", owner))
.ToListAsync();
The first snippet is the trap we find most often. It looks like the safe version, but FromSqlRaw receives an already-built string, so EF has nothing to parameterize. The same applies to ExecuteSqlRaw and SqlQueryRaw.
Parameterized queries with Dapper
Dapper maps properties of an anonymous object to @ parameters and expands lists for IN clauses:
// Fixed: Dapper sends @Owner and @Ids as parameters
var accounts = await conn.QueryAsync<Account>(
"SELECT Id, Balance FROM Accounts WHERE Owner = @Owner AND BranchId IN @Ids",
new { Owner = owner, Ids = branchIds });
// Control the database type when the column is varchar
var p = new DynamicParameters();
p.Add("Owner", owner, DbType.AnsiString, size: 100);
Dapper does not protect you if you concatenate before calling it. conn.Query("... WHERE Owner = '" + owner + "'") is just as vulnerable as raw ADO.NET.
Are stored procedures safe from SQL injection?
Only if they do not build SQL inside. Calling a procedure with parameters is safe; a procedure that concatenates its parameters into EXEC(@sql) moves the injection into the database.
-- Vulnerable
SET @sql = N'SELECT * FROM Accounts WHERE Owner = ''' + @Owner + N'''';
EXEC (@sql);
-- Fixed: sp_executesql with typed parameters
SET @sql = N'SELECT * FROM Accounts WHERE Owner = @Owner';
EXEC sp_executesql @sql, N'@Owner NVARCHAR(100)', @Owner = @Owner;
How to handle dynamic ORDER BY safely
Databases cannot parameterize identifiers such as column names or sort direction. Do not pass them through. Map user input to an allowlist:
private static readonly Dictionary<string, Expression<Func<Account, object>>> SortColumns =
new(StringComparer.OrdinalIgnoreCase)
{
["owner"] = a => a.Owner,
["balance"] = a => a.Balance,
["opened"] = a => a.OpenedOn
};
public IQueryable<Account> Sort(IQueryable<Account> query, string? sortBy, bool desc)
{
// Unknown values fall back to a safe default instead of reaching SQL
var key = SortColumns.GetValueOrDefault(sortBy ?? "", a => a.Owner);
return desc ? query.OrderByDescending(key) : query.OrderBy(key);
}
If you must build SQL text (for example in a reporting module), pick the column name from the same allowlist and wrap it with QUOTENAME on the SQL Server side. The user's string never becomes part of the query.
How to migrate legacy queries safely
- Inventory. Search for
+ "'",FromSqlRaw($,ExecuteSqlRaw($,EXEC(andstring.Formatnear SQL keywords. Your SAST report is a good starting list; see how we triage large reports. - Fix the helpers first. One shared method often covers hundreds of call sites.
- Pin behavior with tests. Run the same inputs before and after, including apostrophes,
%,_, empty strings and very long values. - Match types. Use the column's real type and size so query plans do not change.
- Block regressions. Add a banned-API rule or a PR checklist item for raw SQL.
Parameters stop injection, but input validation still matters for business rules and length limits. We cover that in input validation end to end.
Pitfalls
- Passing an interpolated string to a
...Rawmethod. - Assuming stored procedures are safe by definition.
- "Sanitizing" by removing quotes, which breaks real names and does not stop numeric injection.
- Parameterizing values but concatenating
ORDER BY, table names orTOPclauses. - Connecting with an account that has
db_owner, which turns any injection into a full compromise.
Checklist
- No user input concatenated or interpolated into SQL text.
FromSql/ExecuteSqlby default; every...Rawcall reviewed.- Explicit parameter types and sizes in ADO.NET and Dapper.
- Dynamic identifiers resolved through an allowlist.
- Stored procedures use
sp_executesqlwith parameters. - Least-privilege database login.
Key takeaways
- Parameters separate code from data; escaping does not.
FromSqlRaw($"...")looks safe and is not.- Identifiers need allowlists, not parameters.
- Fix shared helpers first and pin behavior with tests.
Sources
- OWASP SQL Injection Prevention Cheat Sheet
- Microsoft Learn: SQL Queries in EF Core
- Microsoft Learn: sp_executesql
- Dapper on GitHub
Need help fixing SQL injection in your .NET app?
Santhor audits and remediates existing .NET and SQL Server applications: we find concatenated queries, replace them with parameterized EF Core, Dapper or ADO.NET code, and keep results identical while we do it. We are based in Costa Rica and work nearshore with teams in the U.S. and Latin America. Tell us about your project.