How to execute sql query in entity framework core using c#

To execute an SQL query in Entity Framework Core using C#, you can use the FromSqlRaw() or FromSqlInterpolated() method.

Here’s an example of using FromSqlRaw():

var dbContext = new MyDbContext();

var results = dbContext.MyEntities.FromSqlRaw("SELECT * FROM MyTable").ToList();

In this example, MyDbContext is your DbContext class that is responsible for interacting with the database, MyEntities is the DbSet of entities you want to query, and MyTable is the name of the table you want to query.

You can use parameterized queries with FromSqlRaw() as well:

var param = "someValue";
var results = dbContext.MyEntities.FromSqlRaw("SELECT * FROM MyTable WHERE Column = {0}", param).ToList();
Alternatively, you can use FromSqlInterpolated() to write parameterized queries in a more type-safe way:
var param = "someValue";
var results = dbContext.MyEntities.FromSqlInterpolated($"SELECT * FROM MyTable WHERE Column = {param}").ToList();

Make sure to sanitize any input used in your query to prevent SQL injection attacks.

Leave a comment