How do I Use FastMember to create a reader of an object with child object

c# fastmember idatareader sqlbulkcopy

Question

We need to SQLBulkCopy a collection that we have. And since we need an IDataReader to use SQLBulkCopy, I tried to use FastMember for that. As I understand, we can use FastMember to create an IDataReader from an IEnumerable.

So my code reads-

using (var reader = ObjectReader.Create(customer.Records)
{
    DataAccess.BulkInsert(serverName, databaseName, tableName, reader);
}

But the issue is that each record has a child object called which has further properties in it that i want to have in data reader so that they can be inserted into the table in database. But cant find a way to get a flatten IDataReader

Accepted Answer

I fixed this issue by creating an anonymous object and filling it up with the values that we needed. This way you can flatten out your object and use only the properties that you need.

var newObjects = customer.Records.Select(record => new
{
    customer.Id,
    record.DisplayName,
    record.TotalCount,
    record.Conditions.IsActive,
    record.Conditions.SusperCondition.IsSuper,
    Status = (int)record.Status
});

Then just pass this new object to ObjectReader

using (var reader = ObjectReader.Create(newObjects))
{
    DataAccess.BulkInsert(serverName, databaseName, tableName, reader, SetBulkCopyMappings);
}

Bulk Insert -

internal static void BulkInsert(string serverName, string databaseName, string tableName, IDataReader dataReader, Action<SqlBulkCopy> setMappings)
    {
        using (var bulkCopy = new SqlBulkCopy(BuildConnectionString(serverName, databaseName)))
        {
            bulkCopy.DestinationTableName = tableName;
            setMappings(bulkCopy);
            bulkCopy.WriteToServer(dataReader);
        }
    }



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why