MVC 3 - The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

删除回忆录丶 提交于 2019-11-30 21:33:00

Be eager in the controller and call .ToList() before disposing in order to schedule the execution of the query immediately before you have left the using block (as after that it is too late, the context is gone):

using (MyEntities db = new MyEntities())
{
    var model = 
        from c in db.Categories
        select new Category 
        { 
            CategoryID = c.CategoryID, 
            Name = c.Name 
        };
    return View(model.ToList()); // <-- .ToList() here
}

Now, while this will solve your particular problem, what developers or dependency injection frameworks usually do is to instantiate the DbContext inside the BeginRequest event, store it inside the HttpContext.Items so that it is available throughout the execution of the entire request and inside the EndRequest method, retrieve it from HttpContext and dispose it.


UPDATE:

Also it is a good practice to use a view model containing only the properties you would like to use in this particular view:

public class CategoryViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and then inside your action:

public ActionResult Index()
{
    using (MyEntities db = new MyEntities())
    {
        var model = 
            from c in db.Categories
            select new CategoryViewModel
            { 
                Id = c.CategoryID, 
                Name = c.Name 
            };
        return View(model.ToList());
    }
}

and in the view:

@model IEnumerable<MyProject.Models.CategoryViewModel>

@foreach (var category in Model)
{
    <p>
        Id: @category.Id 
        Name: @category.Name
    </p>
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!