flawopen.com/SQL Injection in C#/Entity Framework

Is Entity Framework's FromSqlRaw safe?

Reference page — draft, pending review
Short answer

Only if you pass values as separate parameters. Prefer FromSqlInterpolated instead — it accepts an interpolated string but auto-converts each interpolated value into a real bound parameter.

UNSAFE — FromSqlRaw + concatenation
context.Users.FromSqlRaw(
  "SELECT * FROM Users WHERE Id = " + id
)
SAFE — FromSqlInterpolated
context.Users.FromSqlInterpolated(
  $"SELECT * FROM Users WHERE Id = {id}"
)
// EF intercepts the interpolation,
// binds id as a real parameter

The counterintuitive part

FromSqlInterpolated looks like it should be less safe than FromSqlRaw — it's the one taking an interpolated string. EF Core special-cases this: it intercepts the interpolation at compile time and treats each value as a parameter, rather than baking it into the SQL text. FromSqlRaw with parameters (FromSqlRaw("... WHERE Id = {0}", id)) is also safe — the unsafe pattern is specifically FromSqlRaw combined with manual string concatenation.

How to check your codebase

grep -rn "FromSqlRaw(" --include="*.cs" . | grep '+\|\$"'

FAQ

Is standard LINQ (Where, FirstOrDefault) always safe?

Yes — EF Core's LINQ provider parameterizes automatically. The risk is confined to the raw-SQL methods.

References