-3

i want to insert 10000+ rows in my database fast (I tried with linqtosql and it took me more than 2 minutes) and after a research on the internet I found out about SQL Bulk Copy, but I am don't really understand it. Can someone give me a good example in my case? I fill a list from a .csv file so all my data are in this

List<myTable> datalist = new List<myTable>();

and I also have a context in order to execute SQL transactions.

2
  • Check a tutorial, create a new project using new database and do the bulk copy. After understanding the tutorial start implementing it in your case. Commented Jul 7, 2017 at 12:26
  • Really helpful advice lol Commented Jul 10, 2017 at 13:57

1 Answer 1

1

To use SqlBulkCopy you need either DataTable or an IDataReader. If you have a List<T>, that can still work - via tools like FastMember which makes an IDataReader from a sequence of objects, for example:

using(var bcp = new SqlBulkCopy(connection)) 
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description")) 
{ 
  bcp.DestinationTableName = "SomeTable"; 
  bcp.WriteToServer(reader); 
}

(obviously use datalist in place of data; the strings afterwards are the members to map into columns - you could use nameof here in recent versions of C#, i.e. nameof(myTable.Id) in place of "Id")

If you want to work directly from the CSV without the List<T> in the middle, CsvReader would be more appropriate.

Sign up to request clarification or add additional context in comments.

3 Comments

"The name 'ObjectReader' does not exist in current context"
@L.Achilles yeah, that's an example of using FastMember - to use that you'll need to install FastMember from nuget
Oh, unfortunately I can't download new nuget packages because I can't have any internet access with that pc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.