C# Interview Question #184
What is SQL injection, and how does EF Core help prevent it?
Testing, Security, APIs & Reliability Senior Advanced
Quick Interview Answer
SQL injection occurs when untrusted input is treated as executable SQL syntax rather than data.
Detailed Explanation
SQL injection occurs when untrusted input is treated as executable SQL syntax rather than data.
LINQ queries in EF Core normally generate parameterized SQL, which helps prevent injection when user input is passed as values.
Risks can return when developers construct raw SQL by concatenating or interpolating untrusted strings incorrectly. Raw SQL APIs should use parameterization, and dynamic identifiers such as column names require strict allow-listing because they cannot generally be parameterized like values.
Code Example
// Parameterized through LINQ
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Email == email);
// Avoid building SQL like:
// "SELECT * FROM Users WHERE Email = '" + email + "'";