frc frc - 25 days ago 14
C# Question

issue with using DbContext and returning view with the model

I need to fetch something from the database and return that with the model if

ModelState
is not valid, however I seem to not be able to use
using
and I want to.

So this code works:

[HttpPost]
public ActionResult EditProduct(ProductVM productVM, HttpPostedFileBase file)
{
// Check model state
if (!ModelState.IsValid)
{
Db db = new Db();
productVM.Categories = new SelectList(db.Categories, "Id", "Name");

return View(productVM);

}

return View(productVM);
}


And this code throws the following error:

The operation cannot be completed because the DbContext has been disposed.

[HttpPost]
public ActionResult EditProduct(ProductVM productVM, HttpPostedFileBase file)
{
// Check model state
if (!ModelState.IsValid)
{
using (Db db = new Db())
{
//Db db = new Db();
productVM.Categories = new SelectList(db.Categories, "Id", "Name");
}

return View(productVM);

}

return View(productVM);
}


Can I somehow use
using
and still have it work?

Answer

As @Stephen Muecke said you must materialize the collection using ToList() or AsEnumerable(). If you don't enumarate the collection, it won't run immediately. That's why you are getting that error. So it should be;

productVM.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");

Hope helps,

Comments