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

asp.net-core asp.net-core-1.0 entity-framework-core

Question

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)?

1
4
5/12/2016 6:56:17 AM

Accepted Answer

.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.

1
5/18/2017 1:54:23 PM

Popular Answer

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;
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow