How can I make a big insertion with SqlBulkCopy from a List<> of simple object ?
Do I implement my custom IDataReader ?
The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.
BatchSize = 4000; By default, SqlBulkCopy will process the operation in a single batch. If you have 100000 rows to copy, 100000 rows will be copied at once. Not specifying a BatchSize can impact your application: Decrease SqlBulkCopy performance.
Upload the data to the temporary table, then perform the SqlBulkCopy update. Using SqlBulkCopy(), upload the datatable's data to the temporary table. Then execute a SQL command to update the main table's data from the temporary table. Finally drop the temporary table.
SqlBulkCopy lets you bulk load a SQL Server table with data from another source. This means that it copies (in bulk) data from another source into an SQL database table.
With FastMember, you can do this without ever needing to go via DataTable
(which, in my tests, more-than-doubles the performance):
using(var bcp = new SqlBulkCopy(connection)) using(var reader = ObjectReader.Create(data, "Id", "Name", "Description")) { bcp.DestinationTableName = "SomeTable"; bcp.WriteToServer(reader); }
Note that ObjectReader
can also work with non-generic sources, and it is not necessary to specify the member-names in advance (although you probably want to use the ColumnMappings
aspect of SqlBulkCopy
if you don't specify them in the ObjectReader
itself).
Simply create a DataTable from your list of objects and call SqlBulkCopy.WriteToServer
, passing the data table.
You might find the following useful:
For maximum performance with SqlBulkCopy, you should set an appropriate BatchSize. 10,000 seems to work well - but profile for your data.
You might also observe better results when using SqlBulkCopyOptions.TableLock.
An interesting and informative analysis of SqlBulkCopy performance can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With