Я вызываю метод в Task.Run(() => AircraftManager.UploadAircraft(fileContent));
внутри метода, который я делаю BulkInsert()
, но он не добавляет записи в базу данных.Тем не менее, если я запускаю без Task.Run()
, он отлично работает, но это занимает больше времени.
Примечание. Загрузка Aircraft-2019.csv содержит более 22 000 записей.
Вот мой код
Controller.cs
[HttpPost]
public IHttpActionResult UploadAircraft()
{
//If the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = currentRequest.Value.Content.ReadAsMultipartAsync(new Classes.Mach.AuthorizationServer.API.Providers.MultipartFormDataStreamProvider()).Result;
IList<HttpContent> receivedfiles = provider.Files;
//Upload multiple files
List<FileUploadResult> uploadResults = new List<FileUploadResult>();
foreach (HttpContent file in receivedfiles)
{
var receivedFileName = file.Headers.ContentDisposition.FileName.Trim('\"');
var receivedkey = file.Headers.ContentDisposition.Name.Trim('\"');
byte[] fileContent = file.ReadAsByteArrayAsync().Result;
Task.Run(() => AircraftManager.UploadAircraft(receivedkey, receivedFileName, fileContent));
}
return Ok(new ApiResponse(true, "Files uploaded successfully", uploadResults));
}
AircraftManager.cs
public void UploadAircraft(string documentType, string filename, byte[] content)
{
if (filename.ToLower().EndsWith("csv"))
{
using (MemoryStream stream = new MemoryStream(content))
{
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
var records = csvReader.GetRecords<AircraftDTO>();
List<Aircraft> aircraftList = new List<Aircraft>();
foreach (var item in records )
{
Aircraft aircraft = new Aircraft();
aircraft.BusinessName = item.BusinessName;
aircraft.IssuingCountry = item.IssuingCountry;
aircraft.CertificateCode = item.CertificateCode;
aircraft.CertificateHolderName = item.CertificateHolderName;
aircraft.Tailnumber = item.Tailnumber;
aircraft.SerialNumber = item.SerialNumber;
aircraft.YearMade = !string.IsNullOrWhiteSpace(item.YearMade) && item.YearMade != "NULL" ? Convert.ToInt32(item.YearMade) : (int?)null;
aircraft.Manufacturer = item.Manufacturer
aircraftList.Add(wyvernAircraft);
}
dbContext.Aircraft.BulkInsert(aircraftList);
}
}
}
}