Created
March 8, 2016 19:22
-
-
Save jnm2/a5da01fe2d27fa251090 to your computer and use it in GitHub Desktop.
This file contains 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 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