With Entity Framework Core, you can drop to the original SQL query when using a relational database. When the required query cannot be represented in LINQ, the raw SQL query can be used. You can also use raw SQL queries if using LINQ queries is causing inefficient SQL queries. The raw SQL query can return a generic entity type or a keyless entity type in the model.
Recap: Executing SQL statements and stored procedures with Entity Framework (EF).
Perform SQL statement queries, updates, and deletes, and invoke stored procedures and views using the following methods:
- FromSqlRaw
- FromSqlInterpolated
- ExecuteSqlRaw
- ExecuteSqlInterpolated
FromSqlRaw and FromSqlInterpolated are mainly used for query operations ExecuteSqlRaw and ExecuteSqlInterpolated perform add, update, and delete operations on the database, and return the number of affected rows
The end is an interpolated keyword, which is usually a parameter addition, deletion, modification and check, and a way to resist SQL injection attacks using string interpolation syntax. For example:
Output a SQL statement, the query conditions are not passed through splicing, as shown in the figure below:
There are a few limitations to be aware of when using native SQL queries:
SQL queries must return data for all attributes of the entity type. The column names in the result set must match the column names to which the attributes are mapped. Note that this behavior is different from EF6. The attribute/column mapping relationship of the original SQL query is ignored in EF6, and the result set column names must match the attribute names. SQL queries cannot contain associated data. However, in many cases, you can use the Include method immediately after the query to return correlated data (see Include Associative Data).
(End)
|