Reputation: 4116
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
Upvotes: 1
Views: 1419
Reputation: 4116
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);
}
}
Upvotes: 2