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

前端 未结 1 760
悲&欢浪女
悲&欢浪女 2021-01-06 01:58

I\'m very new to C# and MVC in general and I\'ve been creating my own little blog site as a test project. Although most things are working up to this point, I have had prob

1条回答
  •  难免孤独
    2021-01-06 02:48

    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
    
    @foreach (var category in Model)
    {
        

    Id: @category.Id Name: @category.Name

    }

    0 讨论(0)
提交回复
热议问题