Created
March 12, 2019 13:14
-
-
Save khalidabuhakmeh/7310ab2340a7bef43c7307598c8fe101 to your computer and use it in GitHub Desktop.
EF MultipleResults with SqlParameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.