Home >Database >Mysql Tutorial >How Can I Efficiently Bulk Insert Data from a List into SQL Server Using SqlBulkCopy?
Inserting Data from a List Using SqlBulkCopy
When faced with the task of performing a bulk insertion using SqlBulkCopy from a generic list, it's natural to consider implementing a custom IDataReader. However, there's a more efficient and convenient solution using the FastMember library.
Solution with FastMember
FastMember provides a powerful class called ObjectReader that simplifies the process of converting a list of objects into a data reader. Here's how you can use it:
using(var bcp = new SqlBulkCopy(connection)) using(var reader = ObjectReader.Create(data, "Id", "Name", "Description")) { bcp.DestinationTableName = "SomeTable"; bcp.WriteToServer(reader); }
In this example, data is a list of objects containing the properties "Id," "Name," and "Description."
ObjectReader can also work with non-generic data sources, and it's not necessary to specify the member names in advance. However, if you don't specify them in ObjectReader, you may want to use the ColumnMappings aspect of SqlBulkCopy to define the mapping between the object properties and the destination columns.
The above is the detailed content of How Can I Efficiently Bulk Insert Data from a List into SQL Server Using SqlBulkCopy?. For more information, please follow other related articles on the PHP Chinese website!