Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save khalidabuhakmeh/7310ab2340a7bef43c7307598c8fe101 to your computer and use it in GitHub Desktop.
Save khalidabuhakmeh/7310ab2340a7bef43c7307598c8fe101 to your computer and use it in GitHub Desktop.
EF MultipleResults with SqlParameters
public static class MultipleResultSets
{
public static MultipleResultSetWrapper MultipleResults(
this DbContext db,
string storedProcedure,
params SqlParameter[] parameters
)
{
return new MultipleResultSetWrapper(db, storedProcedure, parameters);
}
public class MultipleResultSetWrapper
{
private readonly DbContext db;
private readonly string storedProcedure;
private readonly SqlParameter[] parameters;
private readonly List<Func<IObjectContextAdapter, DbDataReader, IEnumerable>> resultSets
= new List<Func<IObjectContextAdapter, DbDataReader, IEnumerable>>();
public MultipleResultSetWrapper(
DbContext db,
string storedProcedure,
SqlParameter[] parameters)
{
this.db = db;
this.storedProcedure = storedProcedure;
this.parameters = parameters ?? Enumerable.Empty<SqlParameter>().ToArray();
}
public MultipleResultSetWrapper With<TResult>()
{
resultSets.Add((adapter, reader) => adapter
.ObjectContext
.Translate<TResult>(reader)
.ToList());
return this;
}
public List<IEnumerable> Execute()
{
var results = new List<IEnumerable>();
using (var connection = db.Database.Connection)
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"EXEC {storedProcedure}";
// add any parameters to command
if (parameters?.Any() == true)
{
command.Parameters.AddRange(parameters);
}
using (var reader = command.ExecuteReader())
{
var adapter = ((IObjectContextAdapter)db);
foreach (var resultSet in resultSets)
{
results.Add(resultSet(adapter, reader));
reader.NextResult();
}
}
return results;
}
}
}
}
@clintonprime
Copy link

clintonprime commented Mar 13, 2019

Thank you very much,

I had to do a bit of editing for it to work for me.

I changed the following

if (parameters?.Any() == true)

to this

if (parameters != null)
I also changed this

command.CommandText = $"EXEC {storedProcedure}";

to this

command.CommandText = "EXEC " + storedProcedure;

In case anyone needs it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment