Link Search Menu Expand Document

DataEntityDataReader


Converts an IEnumerable into a DbDataReader.

Given a method that returns an enumerable of Person:

private void IEnumerable<Person> GetPeople(int count = 10000)
{
    for (var i = 0; i < count; i++)
    {
        yield return new Person
        {
            Name = $"Person-{i}",
            SSN = Guid.NewGuid.ToString(),
            DateInsertedUtc = DateTime.UtcNow
        };
    }
}

Convert it to a DbDataReader:

var people = GetPeople();
using (var reader = new DataEntityDataReader<Person>(people))
{
    // Do the stuffs here
}

Use it like a standard data reader:

while (reader.Read())
{
    // Extract the properties here
}

Or pass it to bulk operations:

using (var connection = new SqlConnection(connectionString))
{
    var people = GetPeople();
    using (var reader = new DataEntityDataReader<Person>(people))
    {
        var insertedRows = connection.BulkInsert("[dbo].[Person]", reader);
    }
}

This class is useful when performing bulk operations (BulkDelete, BulkInsert, BulkMerge, BulkUpdate) with a DbDataReader sourced from an IEnumerable.