错误描述:
系统。ObjectDisposedException: '无法访问已处置的上下文实例。此错误的常见原因是处置上下文实例从依赖注入中解决了这个问题,然后尝试在应用程序的其他地方使用相同的上下文实例。这可能如果在上下文实例上调用"Dispose",则会发生将其包装在using语句中。如果您正在使用依赖注入时,你应该让依赖注入容器来处理处理上下文实例的。对象名称:'AppDbContext'.'
我试图将数据库记录设置为我在控制器文件中创建的两个对象,并将其用于excel报告生成。但是当我点击生成报告按钮时,它给出了这个错误。
以下是控制器方法的代码:private readonly AppDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IWebHostEnvironment _webHostEnvironment;
private static IEnumerable<Feedback> sheetfeedbacks;
public AdminController(AppDbContext db, UserManager<ApplicationUser> userManager, IWebHostEnvironment webHostEnvironment)
{
_db = db;
_userManager = userManager;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult FeedbackMgmt()
{
ParentForApply ParentVM = new ParentForApply();
var records = _db.FeedbackData;
ParentVM.FeedbackList = records;
sheetfeedbacks = records;
return View(ParentVM);
}
public IActionResult ReportFeedback()
{
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Feedback Data");
var CurrentRow = 1;
#region Header
worksheet.Cell(CurrentRow, 1).Value = "Sr. No";
worksheet.Cell(CurrentRow, 2).Value = "Full Name";
worksheet.Cell(CurrentRow, 3).Value = "Suggestions";
worksheet.Cell(CurrentRow, 4).Value = "Contact No";
worksheet.Cell(CurrentRow, 5).Value = "Email Id";
worksheet.Cell(CurrentRow, 6).Value = "City";
worksheet.Cell(CurrentRow, 7).Value = "State";
#endregion
#region Body
foreach (var fback in sheetfeedbacks)
{
CurrentRow++;
worksheet.Cell(CurrentRow, 1).Value = CurrentRow - 1;
worksheet.Cell(CurrentRow, 2).Value = fback.FullName;
worksheet.Cell(CurrentRow, 3).Value = fback.Suggestions;
worksheet.Cell(CurrentRow, 4).Value = fback.ContactNo;
worksheet.Cell(CurrentRow, 5).Value = fback.EmailId;
worksheet.Cell(CurrentRow, 6).Value = fback.City;
worksheet.Cell(CurrentRow, 7).Value = fback.State;
}
#endregion
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(
content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Feedback Data.xlsx"
);
}
}
}
上述错误弹出ReportFeedback()方法。
您在控制器中使用AppDbContext
的唯一地方是在这一行
var records = _db.FeedbackData;
只要你想访问数据库,那么你需要使用Task
&Await
,我怀疑这是导致错误
public async Task<IActionResult> FeedbackMgmt()
{
ParentForApply ParentVM = new ParentForApply();
var records = await _db.FeedbackData.ToListAsync();
ParentVM.FeedbackList = records;
sheetfeedbacks = records;
return View(ParentVM);
}