SQL Injection Prevention Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓SQL Injection Prevention runs in O(n) time and O(n) space, in C# as in every other language.
- ✓System.Data.Common defines the shape (DbCommand, DbParameter) and Microsoft.Data.SqlClient is the current SQL Server implementation, with System.Data.SqlClient as the legacy package.
- ✓AddWithValue is the thing reviewers argue about: it sends nvarchar for every string, forcing an implicit conversion against a varchar column and turning an index seek into a scan, so declare SqlDbType and size.
- ✓The C# trap: EF Core's raw-SQL pair is a genuine C# language trap. FromSqlInterpolated takes a FormattableString and converts every hole into a DbParameter; FromSqlRaw takes a string.
- ✓SqlClient sends parameterised commands through sp_executesql with a typed parameter list, so the plan cache key includes each parameter's declared type and length.
What SQL Injection Prevention actually is
SQL Injection Prevention in C#: what you actually reach for
C# implementation
using Microsoft.Data.SqlClient;
using System.Data;
public static class CustomerSearch
{
// ORDER BY is fixed at parse time, so it is chosen here, not bound.
private static readonly Dictionary<string, string> Sortable = new()
{
["created"] = "CreatedAt",
["name"] = "DisplayName",
};
public static async Task<List<string>> SearchAsync(
SqlConnection conn, string term, string sort, int limit)
{
if (!Sortable.TryGetValue(sort, out var column))
throw new ArgumentException("unsortable column", nameof(sort));
var builder = new SqlCommandBuilder();
var sql = $@"SELECT TOP (@limit) DisplayName FROM dbo.Customer
WHERE DisplayName LIKE @term
ORDER BY {builder.QuoteIdentifier(column)} DESC";
await using var cmd = new SqlCommand(sql, conn);
// Declared type and size keep one cached plan instead of one per length.
cmd.Parameters.Add("@term", SqlDbType.NVarChar, 100).Value = $"%{term}%";
cmd.Parameters.Add("@limit", SqlDbType.Int).Value = limit;
var rows = new List<string>();
await using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
while (await reader.ReadAsync().ConfigureAwait(false))
rows.Add(reader.GetString(0));
return rows;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for SQL Injection Prevention?
System.Data.Common defines the shape (DbCommand, DbParameter) and Microsoft.Data.SqlClient is the current SQL Server implementation, with System.Data.SqlClient as the legacy package. The boundary is cmd.Parameters.Add("@term", SqlDbType.NVarChar, 100).Value = term; AddWithValue exists but infers both type and length from the CLR value. SqlCommandBuilder.QuoteIdentifier covers the identifier case that placeholders cannot. Dapper wraps the same objects, taking an anonymous type of parameters, and in EF Core the pair that matters is FromSqlInterpolated and ExecuteSqlInterpolated versus FromSqlRaw and ExecuteSqlRaw.
What is the most common C# mistake when implementing SQL Injection Prevention?
EF Core's raw-SQL pair is a genuine C# language trap. FromSqlInterpolated takes a FormattableString and converts every hole into a DbParameter; FromSqlRaw takes a string. Write context.Customers.FromSqlRaw($"select * from Customer where Name = '{name}'") and the compiler implicitly converts the interpolated string to a string before the call, so the holes are pasted in as text and nothing warns you: the two methods differ by one word in the name and by everything in behaviour. EF Core 8 exposes the safe case as FromSql, leaving Raw as the suffix to grep for. The same silent conversion happens in any API offering both overloads.
How does SQL Injection Prevention actually perform in C#?
SqlClient sends parameterised commands through sp_executesql with a typed parameter list, so the plan cache key includes each parameter's declared type and length. AddWithValue sizes an nvarchar to the actual string length, minting a separate cached plan for every distinct input length and filling the cache with near-duplicates, whereas a fixed SqlDbType.NVarChar with an explicit size keeps one plan. Dapper emits IL to set parameters, so its per-call overhead is close to hand-written ADO.NET, and the round trip dominates either way. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.