Error displaying information (ObjectContext instance has been deleted)

I am creating an ASP.NET MVC 3 application and I have a model that looks something like this:

public partial class Flavor
{
   // ...
   public string Name { get; set; }
   public bool HasNuts {get; set; }
   public virtual ICollection<SaleData> Sales {get; set;}
   // ...
}

which extracts some data from db as 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 the view, I am doing something like this:

<fieldset>
   <legend>Sales Data</legend>
   @foreach (var sale in Model.Sales)
   {
      <div>Weekly</div>
      <div>@sale.Weekly</div>
   }
</fieldset>

If I do not receive Sales data, my Flavor data is displayed without errors, but adding a call to retrieve a list of sales data causes an error . The ObjectContext instance has been deleted and can no longer be for operations that require a connection. .

, - . , - , , , . PartialView , , , , .

, ToList() Sales . , , , , , . ? , , . ?

+3
2

IceCreamDBFlavors, ObjectContext, , .

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
}
0

, Flavor ( Sales), , .

Sales, .

+2

All Articles