EF Core Multiple Result Sets with Stored Procedures
EF Core has no Translate<T>. Read multiple result sets from a SQL Server stored procedure with NextResultAsync, a fluent helper, or Dapper. EF Core 10.
Back in 2015 I wrote about returning multiple result sets from a stored procedure with Entity Framework 6. People still land on that post, and the code in it doesn’t compile against anything modern. This is the Entity Framework Core 10 version.
The reason to do this hasn’t changed. A stored procedure that returns several result sets pipelines them over one connection in one round trip. If a page needs cats and dogs, one trip beats two. It’s not something I reach for often, but when I do, I want it to work without fighting the framework.
Everything here was run against EF Core 10.0.15 and SQL Server 2022.
What Changed Since EF6?
The EF6 trick relied on this:
((IObjectContextAdapter) db).ObjectContext.Translate<Cat>(reader)ObjectContext, IObjectContextAdapter, and Translate<T> don’t exist in EF Core. There’s no built-in replacement. Database.SqlQuery<T> (added in EF Core 7) can map unmapped types, but it only reads the first result set.
What does still exist is plain ADO.NET, and EF Core gives you the connection through Database.GetDbConnection().
The Data
Same two tables as the original, now with a couple of extra columns. Run this against SQL Server. I use a container locally.
CREATE TABLE [dbo].[Cats]( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NULL, [Lives] [int] NOT NULL)
CREATE TABLE [dbo].[Dogs]( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NULL, [Breed] [nvarchar](50) NULL)
INSERT INTO [dbo].[Cats] ([Name], [Lives]) VALUES ('Whiskers', 9), ('Tom', 7)INSERT INTO [dbo].[Dogs] ([Name], [Breed]) VALUES ('Rex', 'Lab'), ('Fido', 'Pug')GO
CREATE OR ALTER PROCEDURE [dbo].[Pets]ASBEGIN SET NOCOUNT ON;
SELECT Id, Name, Lives FROM Cats; SELECT Id, Name, Breed FROM Dogs;ENDAnd the types we want back. These don’t need to be in your DbContext.
public record CatDto(int Id, string Name, int Lives);public record DogDto(int Id, string Name, string Breed);The Gotcha: SqlQueryRaw Returns Only the First Result Set
The obvious EF Core move is SqlQueryRaw:
var cats = await db.Database .SqlQueryRaw<CatDto>("EXEC dbo.Pets") .ToListAsync();It works. You get two cats and no error. You also silently lose the dogs. EF Core only ever sees the first result set, and there’s no API to advance to the next one.
Ask for the other type and it fails:
var dogs = await db.Database .SqlQueryRaw<DogDto>("EXEC dbo.Pets") .ToListAsync();// InvalidOperationException: The required column 'Breed' was not present// in the results of a 'FromSql' operation.That’s because it’s matching DogDto against the cat columns. One more trap: use SqlQueryRaw, not the interpolated SqlQuery($"..."), for the statement text. If you interpolate the whole statement, EF Core turns it into a parameter and SQL Server answers with Could not find stored procedure 'EXEC dbo.Pets'.
So SqlQuery is out for multiple result sets. Drop down a level.
The Manual Way: GetDbConnection and NextResultAsync
var conn = db.Database.GetDbConnection();await db.Database.OpenConnectionAsync();
await using var cmd = conn.CreateCommand();cmd.CommandText = "dbo.Pets";cmd.CommandType = CommandType.StoredProcedure;
await using var reader = await cmd.ExecuteReaderAsync();
var cats = new List<CatDto>();while (await reader.ReadAsync()){ cats.Add(new CatDto( reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2)));}
await reader.NextResultAsync();
var dogs = new List<DogDto>();while (await reader.ReadAsync()){ dogs.Add(new DogDto( reader.GetInt32(0), reader.GetString(1), reader.GetString(2)));}I call OpenConnectionAsync() on the Database facade so EF Core owns the connection lifetime. It’s small and has no dependencies. The cost is that you map columns by hand, and anything you read this way is not tracked by the change tracker.
The Reusable Way: A Fluent MultipleResults Extension
The 2015 post had a MultipleResults().With<Cat>().With<Dog>() wrapper that returned untyped IEnumerables you had to Cast. Here’s the modern version: async, strongly typed, and it returns a tuple.
using System.Data;using System.Data.Common;using System.Reflection;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Infrastructure;using Microsoft.EntityFrameworkCore.Storage;
public static class MultipleResultsExtensions{ public static MultiReader MultipleResults( this DatabaseFacade facade, string sql, CommandType type = CommandType.Text, params DbParameter[] parameters) => new(facade, sql, type, parameters);
public static T MapByName<T>(this DbDataReader r) where T : new() { var o = new T(); var props = typeof(T).GetProperties( BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props) { int i; try { i = r.GetOrdinal(p.Name); } catch (IndexOutOfRangeException) { continue; }
if (!r.IsDBNull(i)) { p.SetValue( o, Convert.ChangeType( r.GetValue(i), Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType)); } }
return o; }}
public class MultiReader( DatabaseFacade db, string sql, CommandType type, DbParameter[] ps){ public MultiReader<T1> With<T1>(Func<DbDataReader, T1> m) => new(db, sql, type, ps, m);
public MultiReader<T1> With<T1>() where T1 : new() => new(db, sql, type, ps, r => r.MapByName<T1>());}
public class MultiReader<T1>( DatabaseFacade db, string sql, CommandType type, DbParameter[] ps, Func<DbDataReader, T1> m1){ public MultiReader<T1, T2> With<T2>(Func<DbDataReader, T2> m) => new(db, sql, type, ps, m1, m);
public MultiReader<T1, T2> With<T2>() where T2 : new() => new(db, sql, type, ps, m1, r => r.MapByName<T2>());}
public class MultiReader<T1, T2>( DatabaseFacade db, string sql, CommandType type, DbParameter[] ps, Func<DbDataReader, T1> m1, Func<DbDataReader, T2> m2){ public async Task<(List<T1>, List<T2>)> ExecuteAsync( CancellationToken ct = default) { var conn = db.GetDbConnection(); var wasClosed = conn.State != ConnectionState.Open;
if (wasClosed) { await db.OpenConnectionAsync(ct); }
try { await using var cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = type;
var tx = db.CurrentTransaction?.GetDbTransaction(); if (tx != null) { cmd.Transaction = tx; }
foreach (var p in ps) { cmd.Parameters.Add(p); }
await using var r = await cmd.ExecuteReaderAsync(ct);
var a = new List<T1>(); while (await r.ReadAsync(ct)) { a.Add(m1(r)); }
await r.NextResultAsync(ct);
var b = new List<T2>(); while (await r.ReadAsync(ct)) { b.Add(m2(r)); }
return (a, b); } finally { if (wasClosed) { await db.CloseConnectionAsync(); } } }}It joins the ambient transaction, only opens and closes the connection if it was closed, and supports parameters and CommandType. Extending it to three or four result sets means adding another MultiReader<...> class, which is boring but mechanical.
Usage with explicit mappers, which is the fast, trimming-friendly option:
var (cats, dogs) = await db.Database .MultipleResults("dbo.Pets", CommandType.StoredProcedure) .With(r => new CatDto(r.GetInt32(0), r.GetString(1), r.GetInt32(2))) .With(r => new DogDto(r.GetInt32(0), r.GetString(1), r.GetString(2))) .ExecuteAsync();Or the reflection-based convenience version, for classes with a parameterless constructor that match columns by name:
public class CatRow{ public int Id { get; set; } public string Name { get; set; } = ""; public int Lives { get; set; }}
public class DogRow{ public int Id { get; set; } public string Name { get; set; } = ""; public string Breed { get; set; } = "";}
var (cats, dogs) = await db.Database .MultipleResults("dbo.Pets", CommandType.StoredProcedure) .With<CatRow>() .With<DogRow>() .ExecuteAsync();Both returned two cats and two dogs against SQL Server 2022.
The Alternative: Dapper QueryMultipleAsync
If you’d rather not own that code, Dapper already does this. Point it at the connection EF Core gives you:
using Dapper;
var conn = db.Database.GetDbConnection();
using var grid = await conn.QueryMultipleAsync( "dbo.Pets", commandType: CommandType.StoredProcedure);var cats = grid.Read<CatRow>().ToList();var dogs = grid.Read<DogRow>().ToList();That’s the lowest-effort option, at the price of a dependency. If Dapper is already in your project, use it.
Do You Need MARS?
No. This one trips people up because of the name. I ran every example above with a connection string that had no MultipleActiveResultSets setting, and NextResult worked fine.
MARS (Multiple Active Result Sets) lets you have more than one concurrent command or open reader on a single connection, for example looping over one reader while issuing another query on the same connection. Reading several result sets from one command, one after the other, is a different thing and works without it.
Wrapping Up
EF Core dropped Translate<T>, and SqlQuery/SqlQueryRaw only gives you the first result set without telling you. Reach for GetDbConnection() and NextResultAsync() directly, wrap it in a helper if you do it often, or hand the connection to Dapper.
If you want the original, the EF6 version from 2015 is still up. For the older .NET Core take on the same idea, see Multiple Result Sets With .Net Core and SQL Server.
Around the web
Comments
Loading comments from GitHub Discussions…