| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Raw SQL Commands in EF Core
Apr 8, 2023
3 min read

Raw SQL Commands in EF Core

Sponsor this Newsletter

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

  1. Call Store Procedure

  2. Write SQL Queries in LINQ

  3. 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

  1. 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

  1. 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();
  1. 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

  1. The SQL query must return data for all properties of the entity type.

  2. The column names in the result set must match the column names that properties are mapped to.

This article was originally published at https://mwaseemzakir.substack.com/ on Apr 8, 2023 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.