Я звоню в методе 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));
        }

Aircaulmanager.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);
            }
        }
    }
}
1
awais 23 Сен 2019 в 15:11

1 ответ

Лучший ответ

Просто удалите вызов DBContext из внутри MemoryStream, используя блок и заменить dbContext.Aircraft.BulkInsert(aircraftList) с dbContext.BulkInsert(aircraftList), как я сделал ниже:


    List<Aircraft> aircraftList = new List<Aircraft>();
        using (MemoryStream stream = new MemoryStream(content))
        {
                using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
                {
                    var records = csvReader.GetRecords<AircraftDTO>();

                    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.BulkInsert(aircraftList);

3
Tallal Kazmi 23 Сен 2019 в 13:31