0

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?

frc
  • 548
  • 2
  • 10
  • 20
  • 1
    try `db.Categories.ToList();` – Berkay Yaylacı Nov 08 '16 at 11:38
  • Seems to be working! What does that have to do with the DbContext being disposed? – frc Nov 08 '16 at 11:41
  • You do not really need `using`, but if your do then you must materialize the collection using `.ToList()` or `.AsEnumerable()` –  Nov 08 '16 at 11:41
  • 1
    After calling this method, You cannot load the related entity lazily because the db is disposed but if you use **Eager Loading** and `Include` it should works. See here for more details http://stackoverflow.com/questions/36961249/using-include-doesnt-change-the-behavior – Salah Akbari Nov 08 '16 at 11:43
  • Thank you both. So should I just not use `using` from now on at all with EF? It would be easier for me not to use it, but I thought it was recommended, that's why I am pushing it. – frc Nov 08 '16 at 11:43

1 Answers1

0

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,

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37