Raw SQL Commands in EF Core
What are the benefits of using raw SQL commands?
We can use EF Core methods to retrieve/update data from database. By using them we can
-
Call Store Procedure
-
Write SQL Queries in LINQ
-
Combine SQL Query and LINQ
So if you want to call SPs directly via LINQ or you donβt have a way to retrieve/modify data other than SQL Query then these methods are perfect remedy.
Methods
We have following methods
-
FromSqlInterpolated and FromSql
These methods are safe against SQL Injection attack and can be used to call SP and execute queries.
FromSql is used for parameterized queries that return entity types
-
FromRawSql
It is helpful in calling the stored procedures and and writing direct SQL in LINQ.
Be careful when using it , if not used properly it can be prey of SQL Injection attack
It is used for parameterized queries that return entity types or primitive types
var simpleSelect = _context.MdCategories
.FromSqlRaw("SELECT * FROM MD_Category")
.ToList();
var selectWithParam = context.MdCategories
.FromSqlRaw("SELECT * FROM MD_Category WHERE Id = {0}", 1)
.ToList();
var callProcedure = context.MdCategories
.FromSqlRaw("EXECUTE dbo.GetCategories")
.ToList();
-
ExecuteSqlRaw
If we want to perform operation like Insert/Update/Delete then we can use it.
It has async versions as well
var executeOperation = _context.Database
.ExecuteSqlRaw(@"DELETE FROM MD_Category WHERE Id > {0}", 1);
var callProcedure = context.Database
.ExecuteSql($"UpdateCategory @Id={id}, @Name={categoryName}");
Things to keep in mind
-
The SQL query must return data for all properties of the entity type.
-
The column names in the result set must match the column names that properties are mapped to.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place