【问题标题】:Excel file upload failed due 'db' does not exist in the current contextExcel 文件上传失败,因为当前上下文中不存在“db”
【发布时间】:2017-10-26 05:49:45
【问题描述】:

我正在尝试上传 excel 文件,然后显示并将其保存在数据库中。我首先使用实体​​框架代码。如果我显示该文件而不是它工作正常,但如果我尝试将它保存到我当前的数据上下文中,我得到此错误“'db' 在当前上下文中不存在” 任何建议对我来说都是很好的选择。在显示时我想保存相同的 excel 文件。如果我的方法不正确,请点亮我如何将数据表保存到基于对象的类中。 我有一个类文件

public class dataextract
 {

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

}

在数据上下文中

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

}

在控制器中

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

【问题讨论】:

  • 你试过public ReadContext() : base("ExcelConnection")吗?为了清楚起见,还提供ExcelConnection 连接字符串。
  • 是的,我犯了同样的错误
  • 能否请您删除 'using( ) { }' 并尝试不使用 ReadContext db = new ReadContext(); foreach (var ss in query) { db.dataext.Add(ss); } db.SaveChanges();
  • @Samkhan 我做了但是同样的错误

标签: asp.net-mvc excel-reader


【解决方案1】:
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();
                    }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多