Skip to content

Instantly share code, notes, and snippets.

@jnm2
Created March 8, 2016 19:22
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 jnm2/a5da01fe2d27fa251090 to your computer and use it in GitHub Desktop.
Save jnm2/a5da01fe2d27fa251090 to your computer and use it in GitHub Desktop.
public static class DbSetExtensions
{
public static async Task<IReadOnlyList<T>> FromReaderAsync<T>(this DbSet<T> set, DbDataReader reader) where T : class
{
var r = new List<T>();
var materializer = new DbDataReaderMaterializer<T>(set);
while (await reader.ReadAsync())
r.Add(materializer.Materialize(reader));
return r.AsReadOnly();
}
public static IReadOnlyList<T> FromReader<T>(this DbSet<T> set, DbDataReader reader) where T : class
{
var r = new List<T>();
var materializer = new DbDataReaderMaterializer<T>(set);
while (reader.Read())
r.Add(materializer.Materialize(reader));
return r.AsReadOnly();
}
private struct DbDataReaderMaterializer<T>
{
private readonly Func<ValueBuffer, T> materializer;
private readonly IRelationalValueBufferFactory valueBufferFactory;
public DbDataReaderMaterializer(IInfrastructure<IServiceProvider> accessor)
{
var valueBufferParameter = Expression.Parameter(typeof(ValueBuffer));
materializer = Expression.Lambda<Func<ValueBuffer, T>>(
accessor.GetService<IEntityMaterializerSource>().CreateMaterializeExpression(
accessor.GetService<IModel>().FindEntityType(typeof(T)),
valueBufferParameter),
valueBufferParameter).Compile();
valueBufferFactory = accessor.GetService<IRelationalValueBufferFactoryFactory>().Create(new[] { typeof(T) }, null);
}
public T Materialize(DbDataReader currentRecord)
{
return materializer.Invoke(valueBufferFactory.Create(currentRecord));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment