Covers EF Core raw SQL APIs (FromSql/FromSqlInterpolated, FromSqlRaw, SqlQuery and SqlQueryRaw, ExecuteSql and ExecuteSqlRaw), how interpolated strings become parameters, the injection traps with FromSqlRaw and dynamic identifiers, the EF1002 analyser, and composing LINQ over composable SQL versus stored procedures.
Use raw SQL for what LINQ can't express well: hints, window functions, full-text search, table-valued functions or stored procedures. FromSql($"... {id}") takes a FormattableString, so every interpolation hole becomes a DbParameter; that is the safe default. FromSqlRaw takes a plain string and is safe only with explicit @p parameters: passing $"...{input}" to it concatenates the value into SQL, which is SQL injection (EF Core 8's EF1002 analyser warns about it). SqlQuery<T> returns scalars or unmapped DTOs, and ExecuteSql runs commands. Identifiers such as sort columns can never be parameters, so whitelist them. A composable SELECT can have LINQ added on top (EF wraps it as a subquery), but EXEC cannot. The trade-off is power and performance versus losing compile-time checking, so keep raw SQL small and tested.
"I use raw SQL in EF Core when LINQ either can't express the query or produces a plan I can't live with: a
CROSS APPLYto a table-valued function,CONTAINSTABLEfull-text search, a query hint, or an existing stored procedure. EF Core gives me three families.FromSqlon aDbSetreturns entities.Database.SqlQuery<T>returns scalars or, since EF Core 8, any unmapped type.Database.ExecuteSqlruns a command and returns rows affected. Each has aRawtwin.The security point is the type of the argument.
FromSql,SqlQueryandExecuteSqltake aFormattableString, so when I write$"SELECT ... WHERE Id = {id}", the compiler keeps the format and the arguments separate and EF turns each hole into@p0,@p1. TheRawmethods take astring. If someone writesFromSqlRaw($"... WHERE Name = '{name}'"), the interpolation happens before EF sees it, so the value is concatenated into the SQL text. That's classic injection, and it looks almost identical in a review. EF Core 8 added the EF1002 analyser for exactly this. For example, at [company] I [found an admin search that passed a sort column and filter throughFromSqlRawwith string interpolation]; we [fixed it with parameters and a whitelist and added EF1002 as an error], and [the pen test retest came back clean].The second trap is identifiers. You can't parameterise a table name or an
ORDER BYcolumn, so dynamic sorting means mapping the client's value through a whitelist to a known column, never passing it through. On composition: if the SQL is a plainSELECT, EF wraps it as a subquery so I can addWhere,OrderByandInclude. A stored procedure call isn't composable, so I callAsAsyncEnumerable()orToListAsync()straight after it. The mistake I see is treatingFromSqlRawas 'the same thing with more flexibility'. It's the same thing without the seatbelt."
| API | Input type | Returns | Parameters | Composable |
|---|---|---|---|---|
DbSet.FromSql($"...") (EF 7+) / FromSqlInterpolated |
FormattableString |
Entities (tracked) | Automatic | Yes, if a SELECT |
DbSet.FromSqlRaw("... @p0", p) |
string + object[] |
Entities | Manual | Yes, if a SELECT |
Database.SqlQuery<T>($"...") |
FormattableString |
Scalars, unmapped types (EF 8+) | Automatic | Yes (scalar column must be named Value) |
Database.SqlQueryRaw<T>(...) |
string |
Same | Manual | Yes |
Database.ExecuteSql($"...") |
FormattableString |
int rows affected |
Automatic | n/a |
Database.ExecuteSqlRaw(...) |
string |
int |
Manual | n/a |
| Code | Safe? |
|---|---|
FromSql($"... WHERE Name = {name}") |
Yes: @p0 |
FromSqlRaw("... WHERE Name = {0}", name) |
Yes: {0} becomes a parameter |
FromSqlRaw("... WHERE Name = @name", new SqlParameter("@name", name)) |
Yes |
FromSqlRaw($"... WHERE Name = '{name}'") |
No: concatenated |
FromSqlRaw("... ORDER BY " + sortColumn) |
No: identifier injection |
var sql = $"... {name}"; FromSqlRaw(sql) |
No |
Moving a product search from LINQ Contains (a full scan on [1.8M] rows, p95 [1.9 s]) to FromSql with CONTAINSTABLE on a full-text index, then composing .Where(p => p.IsActive).Take(50) on top, brought p95 to [120 ms] while keeping every input parameterised.
Checks that the candidate can use raw SQL in EF Core without introducing SQL injection, and understands composition and mapping rules.
Green flags
FormattableString vs string overloads and why FromSqlRaw($"") is unsafe.SELECT vs non-composable EXEC.Red flags
$"" string is parameterised.$"SELECT * FROM Products WHERE Name = {name} AND Price < {max}"
target type FormattableString -> Format = "... Name = {0} AND Price < {1}"
Args = [name, max]
target type string -> "... Name = Widget AND Price < 10" (already concatenated)
EF Core's FromSql replaces {0}, {1} with @p0, @p1 and adds SqlParameters. The plan is cached once per shape, which also helps performance. Overload resolution is the whole story: the same $"" literal is safe or unsafe depending on the parameter type of the method it is passed to.
var q = db.Products
.FromSql($"SELECT * FROM Products WITH (FORCESEEK) WHERE CategoryId = {cat}")
.Where(p => p.Price < max)
.OrderBy(p => p.Name);
SELECT [p].[Id], [p].[Name], [p].[Price], [p].[CategoryId]
FROM (
SELECT * FROM Products WITH (FORCESEEK) WHERE CategoryId = @p0
) AS [p]
WHERE [p].[Price] < @__max_1
ORDER BY [p].[Name]
Rules: the SQL must be valid as a subquery (no trailing ;, no ORDER BY without TOP), and it must return every column the entity maps, with matching names. EXEC dbo.GetProducts @p0 can't be a subquery, so composing on it throws; call .AsAsyncEnumerable() and filter in memory, or wrap the logic in an inline table-valued function, which is composable and can be mapped with HasDbFunction.
var ids = await db.Database
.SqlQuery<int>($"SELECT Id AS Value FROM dbo.Orders WHERE Status = {status}")
.Where(v => v > lastId) // composes because the column is named Value
.ToListAsync(ct);
var rows = await db.Database
.SqlQuery<SalesRow>($"SELECT Region, SUM(Total) AS Total FROM dbo.Orders GROUP BY Region")
.ToListAsync(ct); // EF Core 8+: unmapped record type
Parameters carry values, not SQL syntax. ORDER BY @col sorts by a constant. Dynamic identifiers need a whitelist (switch to a known column name or, better, to a LINQ OrderBy expression). QUOTENAME in T-SQL is a backstop, not a design.
var total = new SqlParameter("@total", SqlDbType.Decimal) { Direction = ParameterDirection.Output, Precision = 18, Scale = 2 };
await db.Database.ExecuteSqlRawAsync("EXEC dbo.CloseMonth @month, @total OUTPUT",
[new SqlParameter("@month", month), total], ct);
FromSql results are tracked like any query unless you add AsNoTracking(). ExecuteSql bypasses the tracker: entities already loaded keep stale values, so reload or ChangeTracker.Clear() afterwards if you keep using the context.
FromSqlRaw($"... '{name}'") and FromSql($"... {name}"), pass x' OR 1=1 --, and compare the SQL in LogTo output.<WarningsAsErrors>EF1002</WarningsAsErrors> and see the build fail on the unsafe version..Where().OrderBy() on a FromSql and read the generated subquery with ToQueryString().EXEC and read the exception; rewrite as an inline TVF.SqlQuery<MonthlyTotal> record and compare its plan to the equivalent LINQ GroupBy.Safe raw SQL: entities, unmapped DTOs, commands and a whitelisted sort.
namespace Catalogue.Search;
using Microsoft.EntityFrameworkCore;
public sealed record SearchHit(int Id, string Name, int Rank);
public sealed class ProductSearch(CatalogueDbContext db)
{
// FromSql: {term} and {take} become @p0, @p1. Composable, so LINQ is added on top.
public Task<List<Product>> SearchAsync(string term, int categoryId, CancellationToken ct) =>
db.Products
.FromSql($"""
SELECT p.* FROM dbo.Products p
JOIN CONTAINSTABLE(dbo.Products, Name, {term}) ft ON ft.[KEY] = p.Id
""")
.Where(p => p.CategoryId == categoryId && p.IsActive)
.AsNoTracking()
.Take(50)
.ToListAsync(ct);
// SqlQuery<T>: unmapped record (EF Core 8+).
public Task<List<SearchHit>> RankedAsync(string term, CancellationToken ct) =>
db.Database.SqlQuery<SearchHit>($"""
SELECT p.Id, p.Name, ft.[RANK] AS [Rank]
FROM dbo.Products p JOIN CONTAINSTABLE(dbo.Products, Name, {term}) ft ON ft.[KEY] = p.Id
""").ToListAsync(ct);
// ExecuteSql: a command, parameterised, bypasses the change tracker.
public Task<int> ArchiveAsync(DateOnly before, CancellationToken ct) =>
db.Database.ExecuteSqlAsync($"UPDATE dbo.Products SET IsActive = 0 WHERE DiscontinuedOn < {before}", ct);
// Identifiers cannot be parameters: whitelist to an expression, never pass the string through.
public static IQueryable<Product> Sort(IQueryable<Product> q, string? sort) => sort switch
{
"name" => q.OrderBy(p => p.Name),
"price" => q.OrderBy(p => p.Price),
_ => q.OrderBy(p => p.Id)
};
}
// UNSAFE - the interpolation runs before EF sees the string. EF1002 warns.
// db.Products.FromSqlRaw($"SELECT * FROM dbo.Products WHERE Name = '{name}' ORDER BY {sort}");
<!-- Directory.Build.props: make the analyser a build break -->
<PropertyGroup>
<WarningsAsErrors>$(WarningsAsErrors);EF1002</WarningsAsErrors>
</PropertyGroup>
FromSqlRaw or ExecuteSqlRaw. Why it is wrong: the values are concatenated into the SQL text, which is SQL injection. Instead: use FromSql / ExecuteSql with $"", or Raw with explicit parameters.string variable first and passing it to FromSql. Why it is wrong: it either won't compile or, via FromSqlRaw, loses parameterisation. Instead: keep it a FormattableString or use SqlParameters.OrderBy.EXEC stored procedure. Why it is wrong: EF wraps the SQL as a subquery, which EXEC can't be, so it throws. Instead: materialise with AsAsyncEnumerable() first, or use an inline TVF.SELECT only some columns into an entity with FromSql. Why it is wrong: EF requires every mapped column, so it throws at runtime. Instead: return all columns or use SqlQuery<TDto>.ExecuteSql and then continuing with tracked entities. Why it is wrong: the tracker doesn't know the rows changed, so later saves can overwrite them. Instead: ChangeTracker.Clear() or reload.; or ORDER BY without TOP in composable SQL. Why it is wrong: the subquery becomes invalid. Instead: leave ordering to LINQ.Raw SQL in EF Core is a scalpel. I allow it where it earns its keep (full-text, TVFs, hints, existing procedures, reports) and keep it behind a small, tested class, never scattered through handlers. Every raw query gets an integration test against a real SQL Server (Testcontainers) because the compiler can't check it, and a column rename otherwise breaks it at runtime. I make EF1002 a build error and ban Raw methods outside an allow-listed folder through code review or a Roslyn banned-API analyser.
The security reasoning goes beyond injection: parameterised queries also give plan reuse, and the OWASP and ACSC guidance both treat parameterisation as the primary control. Least privilege on the database login (no db_owner for the app) limits the blast radius if something slips through.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| LINQ | Most queries | Translation limits | Hints, full-text, TVFs |
FromSql |
Entity results needing SQL features | No compile-time checking | Simple filters LINQ handles |
SqlQuery<T> |
Reports, scalars, DTOs | Same | When you need tracked entities |
ExecuteSql |
Commands, procedures | Bypasses tracker and interceptors on SaveChanges | When domain logic must run |
| Dapper on the same connection | Large hand-tuned read models | Second library | A handful of queries |
Start from db.Products.AsNoTracking() as an IQueryable<T> and add Where clauses conditionally; each one ANDs into the same SQL WHERE. For OR logic, combine Expression<Func<T,bool>> predicates by rebinding their parameters (or use LinqKit), never Func<T,bool>, which would force in-memory evaluation.
For sorting, map the client's string to a whitelisted dictionary of key-selector expressions and always add ThenBy(x => x.Id) so paging is stable. Cap the page size on the server. Values captured in closures become SQL parameters, so there's no injection risk and plans are reused.
The trade-off: flexible search is easy to compose, but every optional filter combination is a different SQL shape, so index for the common ones and test the translation.
EF Core takes the expression tree built by IQueryable operators, normalises it, translates it into a SQL expression tree using the provider's method translators (so SQL Server, PostgreSQL and SQLite produce different SQL and support different methods), and generates SQL text. The compiled result is cached by query shape, and captured variables become parameters.
GroupBy, and known methods such as string.Contains, StartsWith, DateTime parts and EF.Functions.Like.Select. Anything untranslatable elsewhere throws an InvalidOperationException instead of silently loading the table.ToQueryString() or LogTo.The trade-off: LINQ is expressive, but you must know which C# your provider can turn into SQL.
Create an inline table-valued function in SQL Server, add a method on the DbContext that returns IQueryable<T> via FromExpression(() => Fn(arg)), and register it with modelBuilder.HasDbFunction (supported since EF Core 5). EF Core then translates db.Fn(x).Where(...).Include(...) into SELECT ... FROM dbo.Fn(@p0) WHERE .... Inline TVFs are a single SELECT, so the optimiser expands them into the outer query like a parameterised view and uses real statistics. Multi-statement TVFs allow procedural logic (table variables, loops, several statements) when you genuinely need it, but they're opaque to the optimiser: SQL Server 2017+ interleaved execution helps, yet their row estimates are often poor, so they're usually slower when composed with large queries.
How to tell it (STAR)
**S:** At [company], a pen test of our [case-management] admin portal found SQL injection in the search endpoint, on a database with [~300k] clients' personal information. **T:** I owned the fix and the assessment of whether anything had been exposed. **A:** I reproduced it and saw the search used `FromSqlRaw` with string interpolation, so the term and the sort column went straight into the SQL. I hot-fixed it the same day with `FromSql` and a whitelist for sorting, then found [four] similar calls and fixed those, reduced the app's database login from `db_owner` to read/write only, reviewed [90] days of audit logs with our privacy officer, and made the EF1002 analyser a build error. **R:** The retest came back clean, the logs showed [no exploitation beyond the tester], and the build has blocked [N] unsafe raw SQL calls since.
Last updated 23 Nov 2026.