asp.net - Error displaying details (ObjectContext instance has been disposed) -
i'm building asp.net mvc 3 app , i've got model looks so:
public partial class flavor { // ... public string name { get; set; } public bool hasnuts {get; set; } public virtual icollection<saledata> sales {get; set;} // ... }
which retrieves data db such:
public partialviewresult details(int id) { using (var db = new icecreamdbflavors()) { flavor someflavor = db.flavors.find(id); someflavor.sales = db.sales.where(c => c.flavorid == id).tolist(); return partialview("details", someflavor); } }
over on view this:
<fieldset> <legend>sales data</legend> @foreach (var sale in model.sales) { <div>weekly</div> <div>@sale.weekly</div> } </fieldset>
if don't retrieve sales data, flavor data displays fine no errors, adding call retrieve list of sales data causes error "the objectcontext instance has been disposed , can no longer used operations require connection." occur.
i've read few other posts , guess i'm missing here. believe error happens due lazy loading, @ least based on i've read here , elsewhere. setting breakpoint in controller before returning partialview , checking object, believe, causes evaluation take place, displays want.
i under impression tolist()
call force sales collection filled in. since don't have issue when line's commented out, assume problem still related , when view attempting iterate sales, can't. correct here? guess thought forcing evaluation. how resolve this?
don't dispose icecreamdbflavors class inherits objectcontext, needs have lifetime greater allowed.
change
using (var db = new icecreamdbflavors()) { flavor someflavor = db.flavors.find(id); someflavor.sales = db.sales.where(c => c.flavorid == id).tolist(); return partialview("details", someflavor); }
to
try { var db = new icecreamdbflavors(); flavor someflavor = db.flavors.find(id); someflavor.sales = db.sales.where(c => c.flavorid == id).tolist(); return partialview("details", someflavor); } catch(exception ex) { // log exeption }
Comments
Post a Comment