Cannot convert from system.data.common.dbconnection to system.data,sqlconnection

asp.net-mvc-5 c# entity-framework-6 epplus sqlbulkcopy

Question

I am importing data from my excel file to sql database. I am using MVC 5 and entity framework 6. I am using epplus to import the data and sqlbulkcopy to import the data to sql. I am getting 3 errors: 1) excelImportDBEntities.Database.Connection 2) sqlbulkcopy is a namespace but used as a type 3) ObjectReader

public async System.Threading.Tasks.Task<ActionResult> 
ApplicationAsync(FormCollection formCollection)
    {
        var usersList = new List<bomApplicationImportTgt>();
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["UploadedFile"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                using (var package = new ExcelPackage(file.InputStream))
                {
                    var currentSheet = package.Workbook.Worksheets;
                    var workSheet = currentSheet.First();
                    var noOfCol = workSheet.Dimension.End.Column;
                    var noOfRow = workSheet.Dimension.End.Row;
                    for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                    {
                        var user = new bomApplicationImportTgt();
                        user.date = Convert.ToDateTime(workSheet.Cells[rowIterator, 1].Value);
                        user.Description = workSheet.Cells[rowIterator, 2].Value?.ToString();
                        user.SequenceNumber = Convert.ToInt32(workSheet.Cells[rowIterator, 3].Value);
                        user.PartNumber = workSheet.Cells[rowIterator, 4].Value?.ToString();
                        user.PartsName = workSheet.Cells[rowIterator, 5].Value?.ToString();
                        user.SP = workSheet.Cells[rowIterator, 6].Value?.ToString();
                        user.INT = workSheet.Cells[rowIterator, 7].Value?.ToString();
                        user.SN = workSheet.Cells[rowIterator, 8].Value?.ToString();
                        user.SZ = workSheet.Cells[rowIterator, 9].Value?.ToString();
                        user.C = workSheet.Cells[rowIterator, 10].Value?.ToString();
                        user.E_F = workSheet.Cells[rowIterator, 11].Value?.ToString();
                        user.Block = workSheet.Cells[rowIterator, 12].Value?.ToString();
                        user.SEC = workSheet.Cells[rowIterator, 13].Value?.ToString();
                        user.Item = workSheet.Cells[rowIterator, 14].Value?.ToString();
                        user.SUF = workSheet.Cells[rowIterator, 15].Value?.ToString();
                        user.Model = workSheet.Cells[rowIterator, 16].Value?.ToString();
                        user.M_E_F = workSheet.Cells[rowIterator, 17].Value?.ToString();
                        user.OP = workSheet.Cells[rowIterator, 18].Value?.ToString();
                        user.Type = workSheet.Cells[rowIterator, 19].Value?.ToString();
                        user.Quantity = workSheet.Cells[rowIterator, 20].Value?.ToString();
                        user.PLGRPCD = workSheet.Cells[rowIterator, 21].Value?.ToString();
                        user.PL1 = workSheet.Cells[rowIterator, 22].Value?.ToString();
                        user.ATC1 = workSheet.Cells[rowIterator, 23].Value?.ToString();
                        user.PL2 = workSheet.Cells[rowIterator, 24].Value?.ToString();
                        user.ATC2 = workSheet.Cells[rowIterator, 25].Value?.ToString();
                        user.PL3 = workSheet.Cells[rowIterator, 26].Value?.ToString();
                        user.ATC3 = workSheet.Cells[rowIterator, 27].Value?.ToString();
                        user.Plant = workSheet.Cells[rowIterator, 28].Value?.ToString();
                        user.SHR = workSheet.Cells[rowIterator, 29].Value?.ToString();
                        user.DC_Number = workSheet.Cells[rowIterator, 30].Value?.ToString();
                        user.FileName = fileName;
                        usersList.Add(user);
                    }
                }
            }
        }
        using (Dev_Purchasing_New_ModelEntities excelImportDBEntities = new Dev_Purchasing_New_ModelEntities())
        {
            await new BulkWriter().InsertAsync(usersList, "bomApplicationImportTgt", excelImportDBEntities.Database.Connection, CancellationToken.None);
        }
        return View("Application");
    }

I am trying to get the import to be faster thats why I am using sqlbulkcopy, but I am not able to do so because of these errors.

1
0
5/9/2019 3:04:05 PM

Popular Answer

Please check below code upload excel to SQL bulk upload

Controller Code

    [HttpPost]
    public ActionResult ImportExcel(HttpPostedFileBase postedFile)
     {
      try
        {
          string filePath = string.Empty;
          if (postedFile != null)
          {
            //Save File
            string path = Server.MapPath("~/ExcelUpload/");
            if (!Directory.Exists(path))
            {
               Directory.CreateDirectory(path);
            }
            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);
            //End
            string conString = string.Empty;
            switch (extension)
            {
             case ".xls": //Excel 97-03.
                  conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                  break;
             case ".xlsx": //Excel 07 and above.
                  conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
            }
            //Add Excel Data To Datatable
            DataTable dt = new DataTable();               
            conString = string.Format(conString, filePath);
            //Get Actual Data for Excel
            using (OleDbConnection connExcel = new OleDbConnection(conString))
            {
               using (OleDbCommand cmdExcel = new OleDbCommand())
               {
                  using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                   {
                     cmdExcel.Connection = connExcel;
                     //Get the name of First Sheet.
                     connExcel.Open();
                     DataTable dtExcelSchema;
                     dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                     string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                     connExcel.Close();
                     //Read Data from First Sheet.
                     connExcel.Open();
                     cmdExcel.CommandText = "SELECT * From [" + sheetName + "] Where Name IS NOT NULL AND NOT Name=''";
                     odaExcel.SelectCommand = cmdExcel;
                     odaExcel.Fill(dt);
                     connExcel.Close();
                    }
                 }
              }                   
             //Insert Call Dispositions table bulk upload
             conString = ConfigurationManager.ConnectionStrings["exportDataToExcel"].ConnectionString;
             using (SqlConnection con = new SqlConnection(conString))
             {
              using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                   TempData["TotalInsertCount"] = dt.Rows.Count;
                   foreach (DataColumn col in dt.Columns)
                            col.ColumnName = col.ColumnName.Trim();

                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.CallDispositions";
                    //[OPTIONAL]: Map the Excel columns with that of the database table                       
                     sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                     sqlBulkCopy.ColumnMappings.Add("TAT", "TAT");
                     sqlBulkCopy.ColumnMappings.Add("Discription", "Discription");
                     con.Open();
                     sqlBulkCopy.WriteToServer(dt); //
                     con.Close();
                 }
              }
          //End
        }
      }
     catch (Exception ex)
     {

     }
     return RedirectToAction("List"); }

Connection string for get the excel data and add datatable

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
0
5/10/2019 8:06:16 AM


Related Questions





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