I've read this and this and others like them but I am still getting
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Here's the controller:
public ActionResult Home()
{
HomeViewModel model = new HomeViewModel();
return View(model);
}
Here's the HomeViewModel object:
public class HomeViewModel
{
public virtual ICollection<MenuItem> Menu { get; set; }
public HomeViewModel()
{
using (Core db = new Core())
{
Menu = db.Menu.ToList();
Dashboard = db.Dashboard.ToList<DashboardItem>();
foreach (MenuItem item in Menu)
{
item.Items = (from mi in db.Menu where mi.Parent.MenuItemID == item.MenuItemID select mi).ToList();
}
}
}
}
Here's the Home view:
@model AVP.DAL.HomeViewModel
@{
ViewBag.Title = "Home";
}
<div class="row">
<div class="col-lg-8">@Html.Partial("SidebarP", Model)</div>
<div class="col-lg-8">@Html.Partial("DashboardP", Model)</div>
</div>
And here's the SidebarP partial view:
@model AVP.DAL.HomeViewModel
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav nav-stacked">
@foreach (AVP.DAL.MenuItem mi in Model.Menu.Where(m => m.Menu.Name == "SideBar")) // <-- exception thrown here
{
// whatever
}
</ul>
</div>
The exception is thrown at the foreach but as the link questions suggested, I have called ToList() to force the db access.
I took out the using()
around the DbContext
and that fixed the problem but I don't understand why that should matter when I have brought the data into the model?
Am I putting the application at risk of a memory leak by leaving that using out?
Thanks for any help,
.pd.