2

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.

Community
  • 1
  • 1
stardotstar
  • 318
  • 2
  • 18
  • 1
    The way lazy loading works is that until the foreach is called you've not round tripped to the database. Which means that the context is already disposed. – Cookie Mar 05 '14 at 11:59
  • You might want to rethink your design, take a look at http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application – Cookie Mar 05 '14 at 12:00
  • If you project your query into a flattened model you would avoid this problem. Search for 'LINQ projection' – markpsmith Mar 05 '14 at 12:08
  • www.blackwasp.co.uk has great explanations of LINQ projection and a load of other stuff too if anybody's looking. And that tutorial showing the repository pattern was great. Thank you. – stardotstar Mar 05 '14 at 13:55
  • Have you tried adding .ToList() on the line you are getting the error on? – Termato Oct 07 '14 at 17:50

0 Answers0