Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Created September 14, 2016 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save restlessmedia/5ffdd92510a45ee5b3beee8983d9b0d0 to your computer and use it in GitHub Desktop.
Save restlessmedia/5ffdd92510a45ee5b3beee8983d9b0d0 to your computer and use it in GitHub Desktop.
Entity Framwork GridReader for multiple result sets.
public DataModel GetDataModel(int id)
{
const string sql = "map.GetDataModel @id=@id";
using (DbContext context = new DbContext(_connectionString))
{
using (GridReader reader = new GridReader(context, sql, new SqlParameter("@id", id)))
{
DataModel model = reader.Read<DataModel>().FirstOrDefault();
model.NestedArray = reader.Read<Nested>().ToArray();
return model;
}
}
}
public class GridReader : IDisposable
{
public GridReader(DbContext context, string commandText, params object[] parameters)
{
if (context == null)
throw new ArgumentNullException("context");
if (string.IsNullOrWhiteSpace(commandText))
throw new ArgumentNullException("commandText");
_context = context;
_command = CreateCommand(context.Database.Connection, commandText, parameters);
context.Database.Connection.Open();
_reader = _command.ExecuteReader();
_objectContext = ((IObjectContextAdapter)_context).ObjectContext;
}
public IEnumerable<T> Read<T>()
{
if (_isFirstResult)
_isFirstResult = false;
else
_reader.NextResult();
return _objectContext.Translate<T>(_reader);
}
public void Dispose()
{
_context.Database.Connection.Dispose();
_command.Dispose();
_reader.Dispose();
}
private static DbCommand CreateCommand(DbConnection connection, string commandText, object[] parameters)
{
DbCommand command = connection.CreateCommand();
command.CommandText = commandText;
if (parameters != null && parameters.Length > 0)
{
foreach (object parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
private readonly DbContext _context;
private readonly DbCommand _command;
private readonly DbDataReader _reader;
private readonly ObjectContext _objectContext;
private bool _isFirstResult = true;
}
@restlessmedia
Copy link
Author

Provides a dapper style way of dealing with multiple result sets. Pass in dbcontext, commandtext and parameters and call Read() which returns an Enumerable of the next (or first) result set.

@restlessmedia
Copy link
Author

Does not dispose the dbcontext.

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