Link Search Menu Expand Document

SQL Injection in .NET

Entity Framework is the primary .NET object-relational mapper (ORM). Currently, Entity Framework 6 is used in .NET Framework projects, while Entity Framework Core is the recommended version for .NET Core applications.

Generally speaking, Entity Framework uses LINQ-to-Entities parametrized queries, and it is not susceptible to traditional SQL Injection attacks.

However, Entity Framework does allow for the use of raw SQL queries when working with a relational database, introducing the risk of writing injectable queries. The dangerous methods are:


  • DBSet.SqlQuery()
  • Database.SqlQuery()
  • Database.ExecuteSqlCommand()

EF Core:

  • FromSql()

Vulnerability example

EF Core

The following is a basic raw query designed to find users that match the userEmail parameter.

var result = context.Users.FromSql($"SELECT * from Users WHERE email = '{userEmail}';").ToList();

Since the SQL query is built using interpolation, if the userEmail is provided by the user, an attacker could manipulate the query at her/his discretion.

For example, by injecting ' OR 1 OR ' in the userEmail, the query becomes:

SELECT * from Users WHERE email = '' OR 1 OR '';

The manipulated query returns all the records in the Users table.


Do not use raw SQL queries. When possible, use LINQ to include functions in the query.

EF Core

The query above can be rewritten securely, as follows.

var result = context.Users.Where(u => == userEmail).ToList();


CWE - CWE-89: Improper Neutralization of Special Elements used in an SQL Command

OWASP - SQL Injection

OWASP - SQL Injection Prevention Cheat Sheet

Entity Framework Core - Raw SQL Queries