Using raw SQL queries
Although EF Core can translate most LINQ queries into SQL queries, which is very convenient, sometimes we need to write raw SQL queries if the required query cannot be written in LINQ, or the generated SQL query is not efficient. In this section, we will explore how to use raw SQL queries in EF Core.
EF Core provides several methods to execute raw SQL queries:
FromSql()
FromSqlRaw()
SqlQuery()
SqlQueryRaw()
ExecuteSql()
ExecuteSqlRaw()
When we execute raw SQL queries, we must be careful to avoid SQL injection attacks. Let's see when we should use raw SQL queries and how to use them properly. You can download the sample code from the /samples/chapter7/EfCoreDemo
folder in the chapter's GitHub repository.
FromSql() and FromSqlRaw()
We can use the FromSql()
method to create a LINQ query based on an interpolated string. The FromSql()
method is available in EF Core 7.0 and later versions. There is a similar method...