VirendraJ
VirendraJ

Reputation: 622

How can I implement Bulk insert in ASP.NET Core 1.0?

I want to import the data from database in .csv format and want to export .csv into my SQL server/Oracle database. I am using ASP.NET Core RC 1 at this moment. I looked into SQLBulkCopy class but the issue is that it is not ported to ASP.NET Core.

Can someone tell me how can I do it or is there any other compatible nuget package available (with ASP.NET Core)?

Upvotes: 4

Views: 7098

Answers (2)

Johnathon Sullinger
Johnathon Sullinger

Reputation: 7414

Microsoft has added SqlBulkCopy to .NET Core, so you can bring it in as part of the System.Data.SqlClient NuGet package. I opted to use FastMember by @MarcGravell to handle the work of mapping my data, but you don't have to.

FastMember will take a collection of parameters, and a collection of objects, and pull the values off your objects that map to your collection of parameters. Really simplifies the code.

private async Task OutputPerformanceDataToStorage(List<PerformanceData> dataToSave)
{
    var storageParameters = new[] 
        {
            nameof(PerformanceData.PerformanceId),
            nameof(PerformanceData.IPAddress),
            nameof(PerformanceData.ControllerName),
            nameof(PerformanceData.ActionName),
            nameof(PerformanceData.ActionParameters),
            nameof(PerformanceData.ViewPath),
            nameof(PerformanceData.TotalRequestTimeInMilliseconds),
            nameof(PerformanceData.RequestStartedTimestamp),
            nameof(PerformanceData.RequestEndedTimestamp),
            nameof(PerformanceData.CreatedDateTime),
        };

    var sqlCopy = new SqlBulkCopy(this.connectionString, SqlBulkCopyOptions.Default);
    sqlCopy.DestinationTableName = "[Performance]";

    using (var reader = ObjectReader.Create(dataToSave, storageParameters))
    {
        await sqlCopy.WriteToServerAsync(reader);
    }
}

internal class PerformanceData
{
    public Guid PerformanceId;
    public double TotalRequestTimeInMilliseconds;
    public long RequestStartedTimestamp;
    public long RequestEndedTimestamp;
    public string IPAddress;
    public string ControllerName;
    public string ActionName;
    public string ViewPath;
    public string ActionParameters;
    public List<string> ActionParametersList;
    public DateTime CreatedDateTime;
}

Upvotes: 3

VirendraJ
VirendraJ

Reputation: 622

.NET Standard 2.0 now supports many of the .NET framework libraries which means that SqlBulkCopy class can be used with ASP.NET Core. Dataset, Datatables and SQLBulkCopy will do the job for bulk insertion. Find more details about .NETStandard 2.0 here.

Upvotes: 1

Related Questions