Created
September 14, 2016 08:01
-
-
Save restlessmedia/5ffdd92510a45ee5b3beee8983d9b0d0 to your computer and use it in GitHub Desktop.
Entity Framwork GridReader for multiple result sets.
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 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; | |
} | |
} | |
} |
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 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; | |
} |
Does not dispose the dbcontext.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.