Search code examples
asp.net-mvcexcel-reader

Excel file upload failed due 'db' does not exist in the current context


I am trying upload excel file and then display and save it on database.I am using Entity Framework code first.If I display the file than it is working fine but if I try to save it to my current datacontext I am getting this error "'db' does not exist in the current context" Any suggestion will be great head's up for me.While displaying I want to save same excel file.If my approach is not correct one please light me how do I save datatable to my object based class. I have a class file

public class dataextract
 {

    public string Code { get; set; }
    public string Name1 { get; set; }
    public string Group1 { get; set; }

}

In datacontext

public class ReadContext : DbContext
{
    public ReadContext()
       : base("name = ExcelConnection")
    {
        Database.SetInitializer(new 
          MigrateDatabaseToLatestVersion<ReadContext,      
                 ReadAndDisplayExcel.Migrations.Configuration>());
    }
    public DbSet<dataextract> dataext { get; set; }

}

In Controller

   public ActionResult Index(HttpPostedFileBase uploadfile)
    {
        //List<dataextract> lstStudent = new List<dataextract>();
        if (ModelState.IsValid)
        {
            if (uploadfile != null && uploadfile.ContentLength > 0)
            {
                //ExcelDataReader works on binary excel file
                Stream stream = uploadfile.InputStream;
                //We need to written the Interface.
                IExcelDataReader reader = null;
                if (uploadfile.FileName.EndsWith(".xls"))
                {
                    //reads the excel file with .xls extension
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (uploadfile.FileName.EndsWith(".xlsx"))
                {
                    //reads excel file with .xlsx extension
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }
                else
                {
                    //Shows error if uploaded file is not Excel file
                    ModelState.AddModelError("File", "This file format is not supported");
                    return View();
                }               


                var conf = new ExcelDataSetConfiguration
                {
                    ConfigureDataTable = _ => new ExcelDataTableConfiguration
                    {
                        UseHeaderRow = true
                    }
                };

                DataSet result = reader.AsDataSet(conf);
                DataTable s1 = result.Tables[0];

                reader.Close();                  
                var query = from s in s1.AsEnumerable()

                             select new
                             {

                                 Code = s.Field<string>("Code"),
                                 Name1 = s.Field<string>("Name1"),
                                 Group1 = s.Field<string>("Group1")
                             };

                 using (ReadContext db = new ReadContext())
                 {
                     foreach (var ss in query)//error "'db' does not exist in the current context"
                     {
                         db.dataext.Add(ss);
                     }
                     db.SaveChanges();

                 }

                return View(s1);
            }
        }
        else
        {
            ModelState.AddModelError("File","Please upload your file");
        }
        return View();
  } 

Solution

  • using (ReadContext db = new ReadContext())
                {
                       try
                        {
                            var query = from s in s1.AsEnumerable()
    
                                        select new
                                        {
    
    
                                            CODE = s.Field<string>("CODE").ToString(),
                                            Name = s.Field<string>("Name").ToString(),
                                            Group = s.Field<string>("Group").ToString()
                                        };
                            var q1 = query.Select(x => new dataextract
                            {
    
    
                                CODE = x.CODE,
                                Name = x.CompanyName,
                                Group = x.Group,
                            }).ToList();
    
                            foreach (var ss in q1)
                            {
    
                                db.dataext.Add(ss);
                            }
                            db.SaveChanges();
                        }
                }