Bulk Upload In .NET Core

This article shows how to do bulk upload in .NET Core. Earlier versions of .NET Core did not have any SQLBulkCopy but the latest version of .NET Core does support bulk copy through SQLBulkCopy class.

However, there is no DataTable in .NET Core though which we can do upload, using SQLBulkCopy. .NET Core uses DBDataReader to write the data, using SQLBulkCopy but using DBDataReader is very cumbersome, since you will have to write all the get and set methods and mapping of properties all by yourself.

Thus, we are going to use another class, which will help us to do the bulk uploading in a very easy way.
 
For demo purposes, I will be uploading data from a CSV file, where my data is seperated by "|".
 

Requirements
  1. Visual Studio
  2. .NET Core
  3. SQL Server 
Step 1

Create a .NET Core Console Application.

 
Step 2

Add "appsettings.json" file and add the connection string property. We will use this connection string to connect to the database.
 
 
 
Step 3

Add the code to read the settings from the Configuration Builder. (Find the package list at the bottom of the article).
 
 
 
Step 4

Add the code to read CSV file, which has data for the bulk upload. Read all the lines into a list of the string.
 
 
 
Step 5
 
Create a list of objects 

Here, I am splitting my columns into an object and add the object in a list.

My Employee class is given below.
  1. class Employee  
  2.    {  
  3.        public string EmpId { getset; }  
  4.        public string EmpName { getset; }  
  5.        public decimal Salary { getset; }  
  6.    }   
 
 
Step 6
 
Use SQLBulkCopy to WritetoServer

Here, I am creating a SQLBulkCopy Object. I am using the FastMember ObjectReader class, which creates a DBDataReader object by taking 2 parameters, my employee object list and the type of employee object members. In return, the ObjectReader creates a DBDataReader object, which I can pass in SQLBulkCopy.WriteToServer method.



It's done. Now, run the code and SQLBulkCopy should work on uploading all the records into the database.

Here, the full code is given below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.SqlClient;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. using Microsoft.Extensions.Configuration;  
  8. using FastMember;  
  9.   
  10. namespace BulkCopy  
  11. {  
  12.     public class Program  
  13.     {  
  14.         public static IConfigurationRoot Configuration;  
  15.         public static void Main(string[] args)  
  16.         {  
  17.             var builder = new ConfigurationBuilder()  
  18.                .SetBasePath(Directory.GetCurrentDirectory())  
  19.                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  20.                .AddEnvironmentVariables();  
  21.   
  22.             builder.AddEnvironmentVariables();  
  23.             Configuration = builder.Build();  
  24.             string connectionstring = Configuration["ConnectionString"];  
  25.   
  26.             List<string> records = new List<string>();  
  27.             using (StreamReader sr = new StreamReader(File.OpenRead("C:\\Resources\\Employee.txt")))  
  28.             {  
  29.   
  30.                 string file = sr.ReadToEnd();  
  31.                 records = new List<string>(file.Split('\n'));  
  32.             }  
  33.   
  34.   
  35.             List<Employee> emplist = new List<Employee>();  
  36.   
  37.             foreach (string record in records)  
  38.             {  
  39.                 Employee emp = new Employee();  
  40.                 string[] textpart = record.Split('|');  
  41.                 emp.EmpId = textpart[0];  
  42.                 emp.EmpName = textpart[1];  
  43.                 emp.Salary = Convert.ToDecimal(textpart[2]);  
  44.                 emplist.Add(emp);  
  45.   
  46.             }  
  47.   
  48.   
  49.             var copyParameters = new[]  
  50.              {  
  51.                         nameof(Employee.EmpId),  
  52.                         nameof(Employee.EmpName),  
  53.                         nameof(Employee.Salary)  
  54.                     
  55.                     };  
  56.   
  57.   
  58.             using (var sqlCopy = new SqlBulkCopy(connectionstring))  
  59.             {  
  60.                 sqlCopy.DestinationTableName = "[Employee]";  
  61.                 sqlCopy.BatchSize = 500;  
  62.                 using (var reader = ObjectReader.Create(emplist, copyParameters))  
  63.                 {  
  64.                     sqlCopy.WriteToServer(reader);  
  65.                 }  
  66.             }  
  67.   
  68.   
  69.         }  
  70.     }  
  71.   
  72.     class Employee  
  73.     {  
  74.         public string EmpId { getset; }  
  75.         public string EmpName { getset; }  
  76.         public decimal Salary { getset; }  
  77.     }  
  78.           
  79. }  
The package.json 
  1. {  
  2.   "version""1.0.0-*",  
  3.   "buildOptions": {  
  4.     "emitEntryPoint"true  
  5.   },  
  6.   
  7.   "dependencies": {  
  8.     "Microsoft.Extensions.Configuration""1.1.0",  
  9.     "Microsoft.Extensions.Configuration.FileExtensions""1.1.0",  
  10.     "Microsoft.Extensions.Configuration.Json""1.1.0",  
  11.     "Microsoft.NETCore.App": {  
  12.       "type""platform",  
  13.       "version""1.0.1"  
  14.     },  
  15.     "System.IO.FileSystem""4.3.0",  
  16.     "Microsoft.Extensions.Configuration.EnvironmentVariables""1.1.0",  
  17.     "System.Data.SqlClient""4.1.0",  
  18.     "FastMember""1.1.0"  
  19.   },  
  20.   
  21.   "frameworks": {  
  22.     "netcoreapp1.0": {  
  23.       "imports""dnxcore50"  
  24.     }  
  25.   }  
  26. }  
The CSV Text File  
  1. 111 | Jack1 | 50000    
  2. 112 | Jack2  | 60000    
  3. 113 | Jack3  | 70000    
  4. 114 | Jack4  | 80000     
 
Thanks for reading !! 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now