Advanced
Execute Raw SQL Queries in EF Core
EF Core provides the DbSet.FromSql()
method to execute raw SQL queries and get the results as entity objects.
var users = _context.Users
.FromSql("SELECT * FROM Users")
.ToList();
Limitations
The SQL query must return all the columns of the table. e.g.,
context.Users.FromSql("SELECT username, email FROM Users).ToList();
will throw an exception.
The SQL query cannot include JOIN queries to get related data. Instead
Include()
method can be used to load related entities afterFromSql()
method.
Last updated
Was this helpful?