Use raw SQL when a LINQ query can't express the required operation, such as querying a path within a VARIANT column.
Entity Framework Core provides the following methods for executing raw SQL:
Methods |
Description |
|---|---|
| FromSql, FromSqlRaw | Retrieve entities defined in the model. The SQL query must return all mapped properties of the entity. You can apply LINQ operators, such as Where and OrderBy, to composable SQL queries: Entity Framework Core uses your SQL as a subquery. |
| ExecuteSql, ExecuteSqlRaw | Execute SQL commands and return the number of affected rows. |
| SqlQuery<T>, SqlQueryRaw<T> | Retrieve scalar values or instances of types that aren't mapped in the entity model. For a scalar type, name the column "Value" in double quotation marks: an alias without quotation marks is converted to VALUE, and the query fails with the "invalid identifier" error. |
SqlQuery, SqlQueryRaw, FromSql, and ExecuteSql are available in the provider builds for Entity Framework Core 8 and later. With Entity Framework Core 3.1, use FromSqlInterpolated and ExecuteSqlInterpolated instead of FromSql and ExecuteSql.
The names of the tables and columns created by Entity Framework Core are case-sensitive, so the examples in this topic enclose them in double quotation marks. For more information, see Names of Database Objects.
Use parameters to pass values to raw SQL queries and commands:
The provider sends the values as parameters named :p0, :p1, and so on, not as part of the statement text.
The following example passes a SnowflakeParameter object to FromSqlRaw:
Query semi-structured data
The following example filters customers by a value in a VARIANT column and orders the results using LINQ:
Execute a SQL command
The following example updates a product and returns the number of affected rows:
Retrieve scalar values
The following example retrieves product names without loading Product entities: