Sub topic 15
Running Raw SQL Safely
So far, you have used LINQ to talk to the database, and EF Core wrote the SQL for you. Sometimes you will want to write the SQL yourself. You might need a database feature that LINQ cannot express, or you might already have a query that works well. EF Core lets you do this. This chapter shows how to do it without opening a security hole.
Raw SQL is SQL text that you write by hand and send to the database, instead of letting EF Core generate it from LINQ.
Why Raw SQL Can Be Dangerous
The main risk is SQL injection. SQL injection is an attack where a user types text that the database runs as part of your SQL command. It happens when you glue user input straight into a SQL string.
Picture a search box. The user is supposed to type part of a blog URL. Your code builds the SQL like this:
// DANGEROUS: do not do this
string userInput = "x' OR '1'='1";
string sql = "SELECT * FROM Blogs WHERE Url LIKE '" + userInput + "'";The final SQL becomes ... WHERE Url LIKE 'x' OR '1'='1'. The condition '1'='1' is always true, so every row comes back. A worse input could delete tables.
The fix is a parameter. A parameter is a placeholder in the SQL, such as @p0. The value travels to the database separately from the SQL text, so the database always treats it as data and never as code.
Querying Entities with FromSql
FromSql runs your SQL and turns the rows into entity objects. You call it on a DbSet. It takes an interpolated string, which is a C# string that starts with $ and holds values inside { }.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var pattern = "%example%";
var matching = await db.Blogs
.FromSql($"SELECT * FROM Blogs WHERE Url LIKE {pattern}")
.ToListAsync();
foreach (var blog in matching)
{
Console.WriteLine($"{blog.BlogId}: {blog.Url}");
}The code looks like ordinary string building, but it is safe. FromSql does not accept a plain string. It accepts a FormattableString, which keeps the SQL text and the values apart. EF Core replaces {pattern} with a parameter. The SQL sent to SQLite looks like this:
SELECT * FROM Blogs WHERE Url LIKE @p0The value %example% is sent separately as @p0.
Rules for FromSql
FromSql has a few rules you need to follow:
- The SQL must return every column the entity needs, and the column names must match the property names.
SELECT *from the entity's own table is the simplest way to meet this. - It works only on a
DbSetof an entity type, such asdb.Blogs. - The results are tracked by default, like any other query. Add
.AsNoTracking()if you only want to read them.
Adding LINQ on Top
You can keep writing LINQ after FromSql. EF Core wraps your SQL as a subquery, which is a query nested inside another query, and adds the rest around it.
var recent = await db.Blogs
.FromSql($"SELECT * FROM Blogs")
.Where(b => b.Url.StartsWith("https://"))
.OrderBy(b => b.Url)
.AsNoTracking()
.ToListAsync();This works only when your SQL is a plain SELECT. A stored procedure call cannot be wrapped, so LINQ after it fails.
FromSqlRaw: When You Need a Plain String
Sometimes you must build the SQL text at run time. For that case EF Core offers FromSqlRaw, which takes an ordinary string. Because it takes a plain string, it cannot tell your SQL apart from values you glued into it. You must pass the values separately:
var pattern = "%example%";
var blogs = await db.Blogs
.FromSqlRaw("SELECT * FROM Blogs WHERE Url LIKE {0}", pattern)
.ToListAsync();Here {0} is not C# interpolation. There is no $ in front of the string. EF Core sees {0}, matches it to the first extra argument, and turns it into a parameter.
Here is that check in practice:
var allowedColumns = new HashSet<string> { "Url", "BlogId" };
string sortColumn = "Url"; // imagine this came from the user
if (!allowedColumns.Contains(sortColumn))
{
throw new ArgumentException("Invalid sort column.");
}
var sorted = await db.Blogs
.FromSqlRaw($"SELECT * FROM Blogs ORDER BY {sortColumn}")
.ToListAsync();The $ string is fine here only because the check has already passed. The value can only be one of two safe names.
Queries That Do Not Return Entities
What if you only want a list of URLs, or a count? Database.SqlQuery<T> returns simple values instead of entities. A scalar value is a single plain value, such as a number or a string.
var urls = await db.Database
.SqlQuery<string>($"SELECT Url AS Value FROM Blogs")
.ToListAsync();
var minId = 1;
var count = await db.Database
.SqlQuery<int>($"SELECT COUNT(*) AS Value FROM Blogs WHERE BlogId >= {minId}")
.SingleAsync();Name the output column Value. EF Core expects that name, and it needs it if you add LINQ such as .Where after the query. In EF Core 8 and later, T can also be your own class with properties that match the column names, even if that class is not an entity.
Running Commands with ExecuteSql
To run an UPDATE, INSERT, or DELETE that you wrote yourself, use Database.ExecuteSqlAsync. It returns the number of rows changed.
var newTitle = "Updated title";
var postId = 1;
int rows = await db.Database.ExecuteSqlAsync(
$"UPDATE Posts SET Title = {newTitle} WHERE PostId = {postId}");
Console.WriteLine($"{rows} row(s) changed.");Values are parameterized in the same way as in FromSql. There is also ExecuteSqlRawAsync, which takes a plain string plus separate values, just like FromSqlRaw.
For simple bulk changes, the next chapter covers ExecuteUpdateAsync and ExecuteDeleteAsync. They do the same job with LINQ, so you need no SQL text at all.
Choosing the Right Method
| Goal | Method | Takes | Safe by default? |
|---|---|---|---|
| Get entities with your own SQL | `FromSql` | Interpolated string | Yes |
| Get entities with SQL built at run time | `FromSqlRaw` | Plain string plus values | Only if you pass values separately |
| Get scalars or unmapped types | `Database.SqlQuery<T>` | Interpolated string | Yes |
| Run an UPDATE, INSERT, or DELETE | `Database.ExecuteSqlAsync` | Interpolated string | Yes |
| Run a command built at run time | `Database.ExecuteSqlRawAsync` | Plain string plus values | Only if you pass values separately |
Choose the methods without "Raw" in the name whenever you can. Use the "Raw" versions only when you truly need to build the SQL text at run time.
Common Mistakes
- Building the string first.
var sql = $"... {input}"; db.Blogs.FromSqlRaw(sql)is unsafe. The$string becomes a plain string before EF Core sees it, so the value is pasted in as text and is not a parameter. - Quoting parameters. Writing
'{pattern}'with quotes insideFromSqlis wrong. The parameter already carries its type, so the quotes make the database compare against the literal text@p0. - Missing columns. A
FromSqlquery that leaves out a column the entity needs throws an error when EF Core reads the results.
Exercise
A teammate writes var sql = $"SELECT * FROM Blogs WHERE Url = '{userUrl}'"; var result = db.Blogs.FromSqlRaw(sql).ToList();. Is this safe? How would you fix it?
Show answer
It is not safe. The interpolated string turns into a plain string before FromSqlRaw receives it, so userUrl is pasted straight into the SQL text and enables SQL injection. Fix it with FromSql and no quotes: db.Blogs.FromSql($"SELECT * FROM Blogs WHERE Url = {userUrl}").ToList();. You could also use FromSqlRaw("SELECT * FROM Blogs WHERE Url = {0}", userUrl).
Exercise
Write a query that uses Database.SqlQuery to return the titles of all posts whose BlogId equals a variable blogId.
Show answer
var titles = await db.Database.SqlQuery<string>($"SELECT Title AS Value FROM Posts WHERE BlogId = {blogId}").ToListAsync(); The column is aliased as Value, and blogId becomes a parameter.
Exercise
You run ExecuteSqlAsync to change a post's title, and then you print the Title of a Post object that the same context loaded earlier. The old title appears. Why?
Show answer
ExecuteSqlAsync updates the database directly and skips the change tracker. The Post object already in memory is not refreshed. Call await db.Entry(post).ReloadAsync() or query again to see the new value.