Closed KernelCrap closed 3 months ago
@KernelCrap SqlQuery is not for updates, you can use ExecuteSql or the new ExecuteUpdate.
@ErikEJ ExecuteUpdate does not support returning a value and would require another round-trip to the database. Also, ExecuteUpdate is limited to tables defined in the DbContext.
When you terminate your query with SingleAsync (as opposed to ToListAsync), you're asking EF to generate SQL like the following:
SELECT * FROM (INSERT INTO data (name) VALUES ('foo') RETURNING id) LIMIT 1;
But neither PostgreSQL nor SQL Server allow placing INSERT/UPDATE/DELETE statements in the subquery of a SELECT statement - hence the error message produced by EF. You can perform the Single client-side if you wish, by placing the operator after AsEnumerableAsync() or after ToListAsync().
@roji Thanks. Now I see the underlying problem (and understand the exception). Handling it client-side is fine for our use case.
For it to work in this specific case (with Single directly), EF would have had to wrap the provided SQL in a CTE and produce something like this:
WITH x AS (
UPDATE "Example" SET "Count" = "Count" + 1 WHERE "Id" = 1 RETURNING "Count" AS "Value"
)
SELECT x."Value" FROM x LIMIT 1
For it to work in this specific case (with Single directly), EF would have had to wrap the provided SQL in a CTE and produce something like this
Yep, AFAIK that does work on PostgreSQL, but not on SQL Server (am not sure about other databases). If you want, feel free to open an issue about it (though it will likely take quite a while for that to get worked on, and depends on CTE which EF does not yet support).
The SqlQuery method throws when executing update statements that return a scalar value. This happens on both SQL Server and PostgreSQL with the following SQL:
The above statements work when calling ToListAsync() but throws with SingleAsync(). Examples:
Stack trace:
Runnable example:
Output for the example code:
EF Core version: 8.0.7 Database provider: Microsoft.EntityFrameworkCore.SqlServer (8.0.7) Target framework: NET 8.0 Operating system: Windows 11 23H2 IDE: Visual Studio 2022 17.10.5