SQL Injection Prevention in C# (.NET 10): 8 Attacks I Ran
Last updated: October 28, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401), SQL Server LocalDB 17.0.4025.3, Microsoft.Data.SqlClient 7.1.1, EF Core SqlServer 10.0.14, Dapper 2.1.89, Windows 11
Short answer: SQL injection prevention in C# comes down to one rule: user input goes into a parameter, never into the SQL text. Use SqlCommand.Parameters in ADO.NET, an anonymous object in Dapper, LINQ or FromSql($"...") in EF Core, and sp_executesql with parameters inside stored procedures. Table names, column names and sort directions can’t be parameters, so they come from an allow-list. I ran eight real attacks against a SQL Server database from a .NET 10 app; every one worked against concatenated SQL and every one failed against the parameterized version. The outputs below are copied from those runs.
| Attack I ran | Against | Result | Fix |
|---|---|---|---|
' OR 1=1 -- as the username |
concatenated login query | logged in as admin with no password |
SqlParameter |
' UNION SELECT Username, Password FROM Users -- |
concatenated product search | every username and password in the result | SqlParameter |
999; DROP TABLE AuditLog |
concatenated DELETE | table gone (SQL Server runs both statements) | parameter + least privilege |
' OR 1=1 -- |
EF Core FromSqlRaw($"...") |
all 3 users, build warning EF1002 | FromSql($"...") |
' OR 1=1 -- |
Dapper with an interpolated string | all 3 users, no warning | new { name } |
' OR 1=1 -- |
stored procedure using EXEC(@sql), called with parameters |
all 3 users | sp_executesql with parameters |
| sort column as a parameter | ORDER BY @Sort |
SqlException 1008 | allow-list |
% in a search box |
parameterized LIKE |
all 5 products (not injection, but not what the user typed) | escape [%], [_], [[] |
How I Tested It
One console app (net10.0) recreates a SqliDemo database on LocalDB before each run, with three tables (Users, Products, AuditLog) and three users. Each test calls a vulnerable method and its fixed version with the same input and prints the SQL that was sent and what came back. The passwords are stored as plain text only so the UNION attack has something visible to steal; real passwords must be hashed (see how to hash passwords in C#).
1. Login Bypass: ' OR 1=1 --
This is the classic vulnerable login: the username and password are pasted into the SQL string.
// DANGEROUS: user input concatenated into the SQL text
public static string? LoginUnsafe(SqlConnection connection, string username, string password)
{
string sql = "SELECT Username FROM Users WHERE Username = '" + username +
"' AND Password = '" + password + "'";
Console.WriteLine($"SQL sent: {sql}");
using var command = new SqlCommand(sql, connection);
return command.ExecuteScalar() as string;
}
A wrong password fails as expected. Then two inputs that need no password at all:
SQL sent: SELECT Username FROM Users WHERE Username = 'admin' AND Password = 'guess'
Unsafe, wrong password: (no user)
SQL sent: SELECT Username FROM Users WHERE Username = '' OR 1=1 --' AND Password = 'x'
Logged in as: admin
SQL sent: SELECT Username FROM Users WHERE Username = 'admin' --' AND Password = 'x'
Logged in as: admin
The quote closes the string literal, OR 1=1 makes the condition true for every row, and -- comments out the password check. ExecuteScalar returns the first row, which is usually the first account created: the admin. The second input, admin' --, is worse in practice because it picks the account by name.
The fix: parameters
// SAFE: the values travel as typed parameters
public static string? LoginSafe(SqlConnection connection, string username, string password)
{
const string sql = "SELECT Username FROM Users WHERE Username = @Username AND Password = @Password";
using var command = new SqlCommand(sql, connection);
command.Parameters.Add("@Username", SqlDbType.NVarChar, 50).Value = username;
command.Parameters.Add("@Password", SqlDbType.NVarChar, 100).Value = password;
return command.ExecuteScalar() as string;
}
Safe: (no user)
Safe: (no user)
Safe, real login: admin
The SQL text is a constant, so nothing the user types can change its structure; SQL Server looks for a user literally named ' OR 1=1 --. I used Parameters.Add with an explicit type and size rather than AddWithValue: AddWithValue is just as safe against injection, but it infers nvarchar with the length of each value. After three lookups with AddWithValue (bob, alice, admin), SQL Server’s plan cache held two copies of the same query:
cached plan: (@u nvarchar(5))SELECT Role FROM Users WHERE Username = @u
cached plan: (@u nvarchar(3))SELECT Role FROM Users WHERE Username = @u
With a fixed size there is one plan, and no implicit conversion when the column is varchar.
2. UNION SELECT Dumps the Users Table
A product search with the term concatenated into LIKE:
// DANGEROUS: search box concatenated into LIKE
public static void SearchUnsafe(SqlConnection connection, string term)
{
string sql = "SELECT Name, CAST(Price AS nvarchar(100)) FROM Products WHERE Name LIKE '%" + term + "%'";
using var command = new SqlCommand(sql, connection);
using var reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine($" {reader.GetString(0)} | {reader.GetString(1)}");
}
Normal use, then the same box with a UNION:
Normal search 'mo':
Mouse | 19.50
Monitor 27 | 229.00
100% Cotton Mousepad | 9.99
Injected search:
admin | S3cret!2026
alice | alice-pw
bob | bob-pw
The input was zzz' UNION SELECT Username, Password FROM Users --. zzz matches no product, and the UNION appends rows from a table the page was never meant to read. The attacker doesn’t need to know the column count in advance: a wrong guess returns an error that says so, and they try again.
SqlException 205: All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
3. Stacked Queries: DROP TABLE
An id from the query string, concatenated because “it’s only a number”:
// DANGEROUS: SQL Server runs every statement in the batch
public static void DeleteProductUnsafe(SqlConnection connection, string id)
{
string sql = "DELETE FROM Products WHERE Id = " + id;
Console.WriteLine($"SQL sent: {sql}");
using var command = new SqlCommand(sql, connection);
Console.WriteLine($"Rows affected: {command.ExecuteNonQuery()}");
}
SQL sent: DELETE FROM Products WHERE Id = 999; DROP TABLE AuditLog
Rows affected: 0
SqlException 208: Invalid object name 'AuditLog'.
“Rows affected: 0” looks harmless, but the second statement ran: the next query on AuditLog fails because the table no longer exists. SqlClient sends the whole string as one batch and SQL Server executes every statement in it. Binding the value as an int parameter (or parsing it with int.Parse first) closes this.
4. Error Messages Show the Query Shape
The vulnerable login also breaks for a real customer:
SQL sent: SELECT Username FROM Users WHERE Username = 'O'Brien' AND Password = 'x'
SqlException 102: Incorrect syntax near 'Brien'.
Unclosed quotation mark after the character string ''.
A user named O’Brien can’t log in, and if that exception message reaches the browser, it tells an attacker the input lands inside a quoted string. Log the exception, return a generic error. ASP.NET Core shows exception details only on the developer exception page in Development; if you catch SqlException yourself, don’t copy ex.Message into the response. The IExceptionHandler guide shows how to return a ProblemDetails response without the message.
5. EF Core: FromSqlRaw With $”” Is Not Safe
LINQ queries are parameterized by EF Core. Raw SQL is where it goes wrong, and the method names make the mistake easy. Here are five ways to run the same lookup with the input ' OR 1=1 --:
var linq = db.Users.Where(u => u.Username == name).ToList();
var concat = db.Users.FromSqlRaw("SELECT * FROM Users WHERE Username = '" + name + "'").ToList();
var raw = db.Users.FromSqlRaw($"SELECT * FROM Users WHERE Username = '{name}'").ToList();
var safe = db.Users.FromSql($"SELECT * FROM Users WHERE Username = {name}").ToList();
var placeholder = db.Users.FromSqlRaw("SELECT * FROM Users WHERE Username = {0}", name).ToList();
EF Core’s command log (LogTo with EnableSensitiveDataLogging) shows what reached SQL Server:
--- LINQ
Executed DbCommand (30ms) [Parameters=[@name='' OR 1=1 --' (Size = 4000)], CommandType='Text', CommandTimeout='30']
WHERE [u].[Username] = @name
=> 0 users
--- FromSqlRaw + concatenation
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT * FROM Users WHERE Username = '' OR 1=1 --'
=> 3 users
--- FromSqlRaw + $"" interpolation
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT * FROM Users WHERE Username = '' OR 1=1 --'
=> 3 users
--- FromSql + $"" interpolation
Executed DbCommand (3ms) [Parameters=[p0='' OR 1=1 --' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SELECT * FROM Users WHERE Username = @p0
=> 0 users
--- FromSqlRaw + {0} placeholder
Executed DbCommand (0ms) [Parameters=[p0='' OR 1=1 --' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SELECT * FROM Users WHERE Username = @p0
=> 0 users
The difference between line 3 and line 4 is only the method name. FromSql (and the older FromSqlInterpolated) takes a FormattableString and turns each {value} into a parameter. FromSqlRaw takes a plain string, so the $"" is formatted by C# before EF Core ever sees it. Note also that the safe version has no quotes around {name}; with quotes you’d be comparing against the literal text @p0. The same pairs exist for commands: ExecuteSql is safe, ExecuteSqlRaw with an interpolated string is not, and Database.SqlQuery<T>($"...") is parameterized like FromSql.
The good news: EF Core ships analyzers that catch both unsafe lines at build time, with no configuration:
EfCases.cs(33,31): warning EF1003: Method 'FromSqlRaw' inserts concatenated strings directly into the SQL, without any protection against SQL injection. Consider using 'FromSql' instead, which protects against SQL injection, or make sure that the value is sanitized and suppress the warning.
EfCases.cs(37,28): warning EF1002: Method 'FromSqlRaw' inserts interpolated strings directly into the SQL, without any protection against SQL injection. Consider using 'FromSql' instead, which protects against SQL injection, or make sure that the value is sanitized and suppress the warning.
If your build log has hundreds of warnings, these drown. Make them errors in the project file: <WarningsAsErrors>EF1002;EF1003</WarningsAsErrors>.
IN lists in EF Core 10: ids.Contains(u.Id) with an array is parameterized too. On EF Core 10 the log shows one parameter per element:
Executed DbCommand (33ms) [Parameters=[@ids1='1', @ids2='3'], CommandType='Text', CommandTimeout='30']
WHERE [u].[Id] IN (@ids1, @ids2)
So there’s no reason to build an IN (...) string by hand with string.Join.
6. Dapper: Interpolation Is Just a String
Dapper parameterizes what you pass as the second argument. An interpolated string in the first argument is formatted before Dapper sees it, exactly like FromSqlRaw, but nothing warns you:
// DANGEROUS: Dapper does not touch an interpolated string, it is just a string
var unsafeRows = connection.Query<string>(
$"SELECT Username FROM Users WHERE Username = '{name}'").ToList();
// SAFE: anonymous object -> @name parameter
var safeRows = connection.Query<string>(
"SELECT Username FROM Users WHERE Username = @name", new { name }).ToList();
// SAFE: Dapper expands a list into @ids1, @ids2, ...
var ids = new[] { 1, 3 };
var users = connection.Query<string>(
"SELECT Username FROM Users WHERE Id IN @ids", new { ids }).ToList();
interpolated: 3 rows (admin, alice, bob)
parameter: 0 rows
IN list: admin, bob
Note IN @ids without parentheses: Dapper writes them when it expands the list.
7. Stored Procedures Are Not Automatically Safe
“Use stored procedures” is common advice. This procedure is called from C# with a proper parameter:
CREATE PROCEDURE FindUser_Dynamic @Username nvarchar(50) AS
BEGIN
DECLARE @sql nvarchar(max) = N'SELECT Id, Username, Role FROM Users WHERE Username = ''' + @Username + N'''';
EXEC(@sql);
END
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Username", SqlDbType.NVarChar, 50).Value = username;
FindUser_Dynamic 'alice':
2 alice User
(1 rows)
FindUser_Dynamic "' OR 1=1 --":
1 admin Admin
2 alice User
3 bob User
(3 rows)
The C# side is correct; the injection happens inside the procedure, which concatenates the parameter into dynamic SQL. Search your database for EXEC( and EXECUTE( with a + in the argument. The fix is to pass the value on to sp_executesql as a parameter:
CREATE PROCEDURE FindUser_Safe @Username nvarchar(50) AS
BEGIN
DECLARE @sql nvarchar(max) = N'SELECT Id, Username, Role FROM Users WHERE Username = @u';
EXEC sp_executesql @sql, N'@u nvarchar(50)', @u = @Username;
END
FindUser_Safe "' OR 1=1 --":
(0 rows)
8. ORDER BY Can’t Be a Parameter
Sortable tables are where parameterized code turns back into concatenation. Trying to pass the column as a parameter:
const string sql = "SELECT Name FROM Products ORDER BY @Sort";
SqlException 1008: The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name.
Parameters carry values, not identifiers, so table names, column names and ASC/DESC have to be in the SQL text. Map the request value to SQL you wrote yourself:
static readonly Dictionary<string, string> SortColumns = new(StringComparer.OrdinalIgnoreCase)
{
["name"] = "Name",
["price"] = "Price",
["newest"] = "Id DESC",
};
// SAFE: identifiers come from a fixed list, never from the request
public static void SortWithAllowList(SqlConnection connection, string sort)
{
if (!SortColumns.TryGetValue(sort, out var orderBy))
throw new ArgumentException($"Unknown sort '{sort}'");
string sql = "SELECT Name FROM Products ORDER BY " + orderBy;
using var command = new SqlCommand(sql, connection);
PrintNames(command);
}
Allow-list 'price':
5 rows: 100% Cotton Mousepad, Mouse, USB-C Hub, Keyboard, Monitor 27
ArgumentException: Unknown sort 'Price; DROP TABLE AuditLog'
This is still concatenation, but only of strings from the dictionary. Escaping the column name with QUOTENAME or [...] is a weaker substitute; the allow-list also stops users sorting by columns you didn’t mean to expose.
LIKE Wildcards: Safe, but Not Literal
With a parameter, % can’t inject SQL, but it is still a LIKE wildcard. A user who types % gets every row:
Parameterized, input '%':
5 rows: Keyboard, Mouse, Monitor 27, USB-C Hub, 100% Cotton Mousepad
Escaped, input '%':
1 rows: 100% Cotton Mousepad
On a large table, input like %_%_%_% also makes the query expensive. Escape the three special characters before binding the value:
string escaped = term.Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]");
const string sql = "SELECT Name FROM Products WHERE Name LIKE '%' + @Term + '%'";
In EF Core, string.Contains already does this for you; EF.Functions.Like doesn’t. With the input %:
Executed DbCommand (19ms) [Parameters=[@term_contains='%\%%' (Size = 4000)], CommandType='Text', CommandTimeout='30']
WHERE [u].[Username] LIKE @term_contains ESCAPE N'\'
=> Contains: 0 users
Executed DbCommand (5ms) [Parameters=[@p='%%%' (Size = 4000)], CommandType='Text', CommandTimeout='30']
WHERE [u].[Username] LIKE @p
=> EF.Functions.Like: 3 users
Least Privilege: What It Stopped and What It Didn’t
I reran two attacks as a database user that only has SELECT on Products and Users (switched with EXECUTE AS USER = 'app_reader'):
SQL sent: DELETE FROM Products WHERE Id = 999; DROP TABLE AuditLog
SqlException 229: The DELETE permission was denied on the object 'Products', database 'SqliDemo', schema 'dbo'.
Cannot drop the table 'AuditLog', because it does not exist or you do not have permission.
admin | S3cret!2026
alice | alice-pw
bob | bob-pw
The DROP TABLE was blocked. The UNION dump still worked, because the account needs to read Users to log people in. Least privilege limits the damage; it doesn’t replace parameters. If your app connects as db_owner or sa, every injection becomes the worst case.
Let the Build Find It
Besides EF1002/EF1003 above, the .NET SDK has rule CA2100 for ADO.NET. It is off by default. Turn on the security rules for one build:
dotnet build -p:AnalysisModeSecurity=All
AdoCases.cs(12,29): warning CA2100: Review if the query string passed to 'SqlCommand.SqlCommand(string cmdText, SqlConnection connection)' in 'LoginUnsafe', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
AdoCases.cs(30,29): warning CA2100: Review if the query string passed to 'SqlCommand.SqlCommand(string cmdText, SqlConnection connection)' in 'SearchUnsafe', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
AdoCases.cs(60,29): warning CA2100: Review if the query string passed to 'SqlCommand.SqlCommand(string cmdText, SqlConnection connection)' in 'DeleteProductUnsafe', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
AdoCases.cs(86,29): warning CA2100: Review if the query string passed to 'SqlCommand.SqlCommand(string cmdText, SqlConnection connection)' in 'SortWithAllowList', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
AdoCases.cs(92,29): warning CA2100: Review if the query string passed to 'SqlCommand.SqlCommand(string cmdText, SqlConnection connection)' in 'StoredProcedure', accepts any user input (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2100)
It found all three vulnerable ADO.NET methods (the login, the search and the DELETE), and it also flagged the safe allow-list sort and the stored procedure call, where the command text is a procedure name. CA2100 warns on any non-constant command text; it can’t tell where the string came from. Treat it as a review list, not as proof. It didn’t flag the Dapper interpolation, because that isn’t a SqlCommand in my code.
Keep Microsoft.Data.SqlClient Patched
The first build of this project, with the newest SqlClient (7.1.1) and EF Core SqlServer 10.0.14, printed this:
warning NU1903: Package 'System.Security.Cryptography.Pkcs' 9.0.18 has a known high severity vulnerability, https://github.com/advisories/GHSA-846f-f764-76mx
dotnet nuget why SqliDemo.csproj System.Security.Cryptography.Pkcs
├── Microsoft.Data.SqlClient (v7.1.1)
│ └── System.Security.Cryptography.Pkcs (v9.0.18)
The vulnerable package comes in through SqlClient. Referencing the patched version directly overrides the transitive one:
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
The given project `SqliDemo` has no vulnerable packages given the current sources.
Run dotnet list package --vulnerable --include-transitive in CI so this fails a build instead of scrolling past.
Upgrading from SqlClient 3.x or System.Data.SqlClient? Version 4.0 changed the Encrypt default to true, which breaks many connection strings with “The certificate chain was issued by an authority that is not trusted”.
SQL Injection Prevention Checklist for C#
- No user input in SQL text:
SqlCommand.Parameters, Dapper’s parameter object, LINQ,FromSql/ExecuteSql. - No
FromSqlRaw/ExecuteSqlRawwith+or$""; EF1002 and EF1003 as errors. - Numbers too: an id from the URL goes in as an
intparameter. - Stored procedures: no
EXEC(@sql)with concatenated parameters;sp_executesqlwith a parameter list. - Table, column and sort names from an allow-list.
LIKEinput escaped ([%],[_],[[]) when the user means the literal text.- Database errors logged, not shown to the user.
- The app’s database user can’t
DROP,ALTERor read tables it doesn’t need. dotnet list package --vulnerable --include-transitivein CI.
Further reading: SQL queries in EF Core (Microsoft Learn) and the OWASP SQL Injection Prevention Cheat Sheet.
Related: hash passwords in C# · prevent XSS in ASP.NET Core · OWASP Top 10 for .NET developers · EF Core: the model has pending changes · all C# tutorials