Sub topic 15
Running Raw SQL Safely
LINQ covers most queries you will write. Sometimes, though, you want to write the SQL yourself. You might need a database feature that LINQ can't express, or you might already have a query that works. EF Core lets you run your own SQL and still get entity objects back.
Raw SQL is SQL text that you write by hand instead of letting EF Core generate it.
The Danger: SQL Injection
SQL injection is an attack where a user types SQL code into an input box, and your program runs that code as part of its own query. This happens when you build SQL by joining strings together.
Here is a query that is unsafe:
// DO NOT DO THIS
string userInput = "x' OR '1'='1";
var blogs = await db.Blogs
.FromSqlRaw("SELECT * FROM Blogs WHERE Url = '" + userInput + "'")
.ToListAsync();The input closes the quote early and adds OR '1'='1'. That condition is always true, so the query returns every blog.
The Safe Way: Parameters
A parameter is a value that travels to the database separately from the SQL text. The database always treats it as data and never runs it as code.
FromSql takes an interpolated string, which is a string that starts with $. EF Core turns each {value} into a parameter for you.
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.Url);
}The {pattern} placeholder becomes a parameter, so the database receives something like WHERE Url LIKE @p0. A harmful input is just text that gets compared to Url.
Rules for FromSql
- The SQL must return every column the entity needs, such as
BlogIdandUrlforBlog. - The column names must match the property names.
- You can add LINQ after it. EF Core wraps your SQL inside its own query:
var sorted = await db.Blogs
.FromSql($"SELECT * FROM Blogs WHERE Url LIKE {pattern}")
.OrderBy(b => b.Url)
.ToListAsync();Running Commands That Return No Rows
Sometimes your SQL changes data and returns nothing. For that, use ExecuteSqlAsync. It also turns {value} placeholders into parameters, and it returns the number of rows affected.
var oldUrl = "https://example.com/blog";
var newUrl = "https://example.com/moved";
int rows = await db.Database.ExecuteSqlAsync(
$"UPDATE Blogs SET Url = {newUrl} WHERE Url = {oldUrl}");
Console.WriteLine($"{rows} row(s) changed");ExecuteSqlAsync sends the command to the database right away. It does not use SaveChangesAsync, and it does not update entities the context has already loaded.
| Method | Returns | Use it for |
|---|---|---|
| `FromSql` | Entities | Custom SELECT queries |
| `Database.ExecuteSqlAsync` | Number of rows affected | INSERT, UPDATE, DELETE commands |
Exercise
A coworker writes db.Blogs.FromSqlRaw("SELECT * FROM Blogs WHERE Url = '" + search + "'"). Why is this risky, and how would you rewrite it?
Show answer
The code joins user input into the SQL text, so a user can inject SQL code. Rewrite it as db.Blogs.FromSql($"SELECT * FROM Blogs WHERE Url = {search}"). EF Core then sends search as a parameter.
Exercise
You run ExecuteSqlAsync to rename a blog's URL, but a Blog object you loaded earlier still shows the old URL. Why?
Show answer
ExecuteSqlAsync changes the database directly. It does not update entities the context is already tracking. Reload the entity or query it again to see the new value.