我正在尝试上传 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();
}