skip to content

In EF Core 10, when does FromSqlRaw open an SQL injection hole, and what do the EF1002 and EF1003 analyzer warnings catch?

level: seniorimportance: should knowfreq 46%

answer

  1. string parameter, not FormattableString
  2. $"..." into FromSqlRaw is plain text
  3. {0} placeholders plus params are safe
  4. EF1002 interpolation, EF1003 concatenation
  5. identifiers cannot be parameters

basics

~20 s

FromSqlRaw takes a plain string, so an interpolated or concatenated user value becomes SQL text and can inject. Pass values as {0} placeholders or DbParameter arguments instead. EF1002 warns on interpolation and EF Core 10's EF1003 on concatenation inside raw-SQL calls.

solid answer

~50 s

`FromSqlRaw(string sql, params object?[] parameters)` exists for SQL you must assemble dynamically, and whatever is in `sql` is sent verbatim. The hole opens when a caller-controlled value is put **into that string**: `FromSqlRaw($"... WHERE \"DeviceId\" = {id}")` looks like `FromSql` but the compiler builds a plain `string` before EF sees it, and `"... = '" + name + "'"` is the same thing. Values passed through the `parameters` array, referenced as `{0}`, `{1}` or as named `DbParameter` objects, are bound as parameters and are safe. The EF Core analyzers flag the dangerous shapes: **EF1002**, since EF Core 8, warns when an interpolated string is passed to a raw method; **EF1003**, new in EF Core 10, warns on string concatenation there. Parts that cannot be parameters, such as a column name, must come from a fixed list in code.

code

csharp · 12 lines
csharp
// Safe: values bound as parameters, identifier chosen from code
string column = sortBy switch
{
    "time" => "\"RecordedAt\"",
    "value" => "\"Value\"",
    _ => "\"Id\""
};
var rows = await db.SensorReadings
    .FromSqlRaw(
        "SELECT * FROM \"SensorReadings\" WHERE \"DeviceId\" = {0} ORDER BY " + column,
        deviceId)
    .ToListAsync(ct);

go deeper

for a junior

Know that FromSqlRaw takes a plain string and that putting user input into that string is the classic EF Core injection bug.

for a middle

Explain why $"..." means something different to FromSql and FromSqlRaw, and how {0} placeholders and DbParameter arguments keep values safe.

for a senior

Review raw-SQL call sites, interpret EF1002 and EF1003 warnings, and design dynamic SQL so only code-chosen identifiers are spliced.

for a principal

Make raw-SQL usage auditable: analyzer severity in the build, suppression policy, and ownership of the few dynamic queries the product needs.

## Two methods that look alike EF Core offers two families of raw-SQL methods: | Safe by construction | Raw | Parameter type | |---|---|---| | `FromSql` / `FromSqlInterpolated` | `FromSqlRaw` | `FormattableString` vs `string` | | `Database.SqlQuery<T>` | `Database.SqlQueryRaw<T>` | same split | | `Database.ExecuteSql` / `ExecuteSqlInterpolated` | `Database.ExecuteSqlRaw` | same split | The safe family receives a `FormattableString`: format text and argument values separately, so EF can turn every value into a `DbParameter`. The raw family receives a `string`, which EF sends as written, plus an optional `params object?[]` of values. ## How the hole opens On the IoT platform, a support tool searches readings by device name: ```csharp // Vulnerable: the compiler builds the string before EF sees it var rows = await db.SensorReadings .FromSqlRaw($"SELECT r.* FROM \"SensorReadings\" r JOIN \"Devices\" d ON d.\"Id\" = r.\"DeviceId\" WHERE d.\"Name\" = '{name}'") .ToListAsync(); ``` Because `FromSqlRaw`'s first parameter is `string`, the `$"..."` literal is formatted into an ordinary string first. A `name` of `x' OR '1'='1` changes the statement. The same happens with `+` concatenation or a `string.Format` call. The fixes, in order of preference: 1. **Switch to `FromSql`** with the same interpolated text minus the quotes around `{name}`; now the value becomes `@p0`, and quoting it would turn the placeholder into a string literal. 2. **Keep `FromSqlRaw` but pass values separately**: `FromSqlRaw("... WHERE d.\"Name\" = {0}", name)`. EF replaces `{0}` with a parameter placeholder and binds `name`. 3. **Pass a `DbParameter`** such as `new NpgsqlParameter("name", name)` and reference it by name in the SQL when you need to control its type. ## What the analyzers catch The analyzers that ship with the EF Core package (assembly `Microsoft.EntityFrameworkCore.Analyzers`) include two security warnings: - **EF1002** (since EF Core 8): an interpolated string is passed to a raw-SQL method such as `FromSqlRaw`, `SqlQueryRaw` or `ExecuteSqlRaw`. Its message suggests the safe method instead, and a code fix can switch the call. - **EF1003** (new in EF Core 10): a **concatenated** string is passed to one of those methods. Both are warnings, not errors. If a fragment is trusted, for example a constant chosen from code, you suppress the warning at that call with a comment saying why. Treat a project-wide suppression as a defect. ## Where raw is still needed Parameters can carry **values**, not **identifiers**. A sort column, a table name or `ASC`/`DESC` cannot be bound, so a dynamic report still builds part of the text. The EF-specific rule is simple: only strings chosen by your code, such as entries from a fixed dictionary that maps a request option to a quoted column name, are spliced into a `FromSqlRaw` text; every value still goes through the parameter array. The general theory of why allowlists are the only answer for identifiers belongs to application-security material. ## Same rules for the other raw methods Everything above applies unchanged to the non-entity readers and to commands: | Method | Safe form | Dangerous form | |---|---|---| | Entity query | `FromSql($"... {v}")` | `FromSqlRaw($"... {v}")` | | Scalar or DTO query | `Database.SqlQuery<T>($"... {v}")` | `Database.SqlQueryRaw<T>("..." + v)` | | Command | `Database.ExecuteSqlAsync($"... {v}")` | `Database.ExecuteSqlRawAsync($"... {v}")` | `ExecuteSqlRaw` deserves the most attention in review: a command that runs `DELETE` or `UPDATE` with spliced input can do far more damage than a read, and it often lives in maintenance or admin code paths that get less scrutiny than the main API. ## Review checklist - Search for `FromSqlRaw`, `SqlQueryRaw` and `ExecuteSqlRaw` calls; each one needs a reason to exist. - Any `$` or `+` inside their first argument is a finding unless every spliced piece is code-chosen. - Do not silence EF1002 or EF1003 globally. - Prefer LINQ, then `FromSql`, then `FromSqlRaw`, in that order.

  • Is FromSqlRaw("... WHERE \"DeviceId\" = {0}", deviceId) vulnerable?
    No. The SQL text is a constant, and `deviceId` travels through the `params` array. EF replaces `{0}` with a parameter placeholder and sends the value as a `DbParameter`, exactly as `FromSql` would. The risk exists only when caller data becomes part of the `sql` string itself.
  • A developer stores $"... {name}" in a string variable and passes it to FromSql; what happens?
    It does not compile: `FromSql` accepts only a `FormattableString`, and the variable is a `string`. Developers then sometimes switch to `FromSqlRaw` to make it compile, which is the injection bug. The fix is to pass the interpolated literal directly to `FromSql`, or declare the variable as `FormattableString`.

  • FromSqlRaw($"...{value}") parameterizes the value just like FromSql.
  • Escaping single quotes makes FromSqlRaw concatenation safe.
  • EF1002 and EF1003 are compile errors that block the build.
  • Any value passed in the params array is spliced as text.
  • A column name can be passed as a DbParameter.

Assumes EF Core 10; EF1002 (interpolation in raw-SQL methods) shipped in EF Core 8 and EF1003 (concatenation) is new in EF Core 10.