In an EF Core 10 app on PostgreSQL, how do you call a stored procedure that archives sensor readings and a function that returns readings?
answer
- no result set: Database.ExecuteSqlAsync
- CALL for a PostgreSQL procedure
- set-returning function: FromSql, composable
- SQL Server EXEC is not composable
- uses the context's open transaction
basics
~20 sA procedure that returns no rows runs through Database.ExecuteSqlAsync($"CALL archive_readings({cutoff})"), which returns an int. A function returning reading rows is queried with db.SensorReadings.FromSql($"SELECT * FROM readings_over({deviceId}, {limit})") and, being a SELECT, can be composed with LINQ.
solid answer
~40 sFor a routine that **changes data and returns no result set**, I use `Database.ExecuteSqlAsync`, which takes a `FormattableString`, parameterizes each value and returns the `int` the provider reports for the command. On PostgreSQL a procedure is invoked with `CALL archive_readings({cutoff})`. For a routine that **returns rows of an entity**, I use `FromSql` on the `DbSet`: a PostgreSQL set-returning function is queried as `SELECT * FROM readings_over({deviceId}, {limit})`, which is a normal `SELECT`, so `Where`, `OrderBy` and `Take` compose over it. On SQL Server, `EXECUTE dbo.Proc` cannot be composed, so I put `AsAsyncEnumerable()` straight after `FromSql`. Both calls run on the context's connection and enlist in a transaction started with `Database.BeginTransactionAsync()`, and neither touches the change tracker except that `FromSql` tracks the entities it returns.
code
csharp · 10 linesawait using var tx = await db.Database.BeginTransactionAsync(ct);
await db.Database.ExecuteSqlAsync(
$"CALL archive_readings({cutoff})", ct);
var device = await db.Devices.SingleAsync(d => d.Id == deviceId, ct);
device.LastArchivedAt = cutoff;
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);go deeper
Know that Database.ExecuteSqlAsync runs a command that returns no rows and FromSql runs a query that returns entities.
Explain CALL versus SELECT FROM for PostgreSQL routines, why SQL Server procedures cannot be composed, and how values are parameterized.
Combine routine calls with SaveChanges inside one transaction and handle tracked entities the routine changed behind EF's back.
Decide which logic lives in database routines versus application code, considering testing, deployment of routine changes and portability.
## Two kinds of database routine The IoT platform keeps raw readings for 90 days. Archiving is done by a database routine because it moves rows between tables and updates statistics in one place. Product code also needs readings above a threshold, computed by a database function. EF Core uses different APIs for the two shapes: | Routine returns | EF Core API | Result | |---|---|---| | No rows (does work) | `Database.ExecuteSql` / `ExecuteSqlAsync` | `int` from the provider | | Rows shaped like an entity | `DbSet<T>.FromSql` | `IQueryable<T>`, tracked by default | | Rows of another shape | `Database.SqlQuery<T>` | `IQueryable<T>`, not tracked | ## Calling a procedure that returns nothing ```csharp var cutoff = DateTime.UtcNow.AddDays(-90); await db.Database.ExecuteSqlAsync($"CALL archive_readings({cutoff})", ct); ``` - `ExecuteSqlAsync` takes a `FormattableString`, so `cutoff` is sent as a parameter (`@p0`), exactly like `FromSql`. - It returns the `int` that the underlying `ExecuteNonQuery` reports. For `UPDATE` and `DELETE` statements that is the number of rows affected; for a procedure call it depends on the database and driver, so do not build logic on it without checking. - `ExecuteSqlRaw` is the string-based counterpart for SQL you must assemble dynamically, with the usual injection caveats. On PostgreSQL, **procedures** are invoked with `CALL`; **functions** are called inside a `SELECT`. On SQL Server both are reached with `EXEC` / `EXECUTE`. ## Querying a function that returns rows ```csharp var hot = await db.SensorReadings .FromSql($"SELECT * FROM readings_over({deviceId}, {threshold})") .Where(r => r.RecordedAt >= since) .OrderByDescending(r => r.Value) .Take(50) .ToListAsync(ct); ``` Because the SQL is a `SELECT` from a set-returning function, EF can wrap it as a subquery and add the filter, ordering and limit on the server. The function's columns must cover every mapped property of `SensorReading`, with the mapped names. **SQL Server stored procedures are different**: `EXECUTE dbo.GetReadings @p0` is not valid inside a subquery. Any LINQ operator after it produces invalid SQL, so put `AsAsyncEnumerable()` (or `AsEnumerable()`) immediately after `FromSql`; everything after that runs in .NET. ## Transactions and the change tracker 1. `ExecuteSql` and `FromSql` run on the context's connection. If you called `await db.Database.BeginTransactionAsync()`, they **join that transaction**, so a procedure call and a later `SaveChangesAsync` can commit or roll back together. 2. Without an explicit transaction, each call is its own unit; there is no implicit transaction spanning several calls. 3. `ExecuteSql` does not know which entities the routine changed. Readings already loaded and tracked keep their old values; reload them or use a fresh context after the call. 4. Entities returned by `FromSql` are tracked like any query result unless you add `AsNoTracking()`. ## Testing routine calls Routine calls are only as good as the routine they reach, so they deserve integration tests against a real PostgreSQL instance rather than the in-memory provider, which cannot run SQL at all. A useful test: 1. seeds readings on both sides of the cutoff; 2. calls the code path that runs `ExecuteSqlAsync($"CALL archive_readings({cutoff})")`; 3. asserts on the tables with a fresh context, so stale tracked entities cannot hide a failure. Keep the routine's definition in a migration so the test database and production run the same version of it. ## Parameters the routine expects Pass arguments in the order the routine declares them, with matching types. When the type inferred from the .NET value is not what the routine expects, interpolate a provider parameter object, such as an `NpgsqlParameter` with an explicit `NpgsqlDbType`, instead of the raw value; EF sends it as-is.
- Why does adding .Where(...) after FromSql($"EXECUTE dbo.GetReadings {id}") fail on SQL Server?EF composes by wrapping the raw SQL in a subquery, and SQL Server does not allow `EXECUTE` inside a subquery, so the generated SQL is invalid. Put `AsAsyncEnumerable()` right after `FromSql` so EF sends the procedure call as-is, then filter in .NET, or move the filter into the procedure's parameters.
- After ExecuteSqlAsync archives readings, why can tracked SensorReading entities show stale data?`ExecuteSqlAsync` runs the command on the connection and never informs the change tracker. Entities loaded before the call keep their original values and states. Reload them with `Entry(e).ReloadAsync()`, call `ChangeTracker.Clear()`, or do the follow-up work in a new context.
- ExecuteSqlAsync returns the rows the procedure selects.
- FromSql over any stored procedure can be composed with Where.
- ExecuteSql always runs in its own transaction, ignoring BeginTransaction.
- ExecuteSql updates tracked entities automatically.