c# - issue with using DbContext and returning view with the model -
this question has answer here:
i need fetch database , return model if modelstate not valid, seem not able use using , want to.
so 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 code throws following error:
the operation cannot completed because 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 somehow use using , still have work?
as @stephen muecke said must materialize collection using tolist() or asenumerable(). if don't enumarate collection, won't run immediately. that's why getting error. should be;
productvm.categories = new selectlist(db.categories.tolist(), "id", "name"); hope helps,
Comments
Post a Comment