操作无法完成,因为的DbContext一直使用MVC 4处置 [英] The operation cannot be completed because the DbContext has been disposed using MVC 4

查看:944
本文介绍了操作无法完成,因为的DbContext一直使用MVC 4处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题是问了很多次。我已阅读并实施了所有解决方案,但没有获得成功。当我检索使用EF从数据库中的数据,之后与模型结合使用该模型上查看我收到此错误。

I know that this Question is asked so many times. I have read and implemented all solution but didn't get success. I am getting this error when I retrieve data from database using EF and binds with model after that use this model on View.

我的控制器code是

using System.Linq;
using System.Web.Mvc;
using JsonRenderingMvcApplication.Models;

namespace JsonRenderingMvcApplication.Controllers
{
    public class PublisherController : Controller
    {
        public ActionResult Index()
        {
            PublisherModel model = new PublisherModel();
            using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
            {               
                model.PublisherList = context.Publishers.Select(x =>
                                        new SelectListItem()
                                        {
                                            Text = x.Name,
                                            Value = x.Id.ToString()
                                        }); ;
                           }
            return View(model);
        }

    }
}

我查看code是

My View code is

@model JsonRenderingMvcApplication.Models.PublisherModel

@{
    ViewBag.Title = "Index";
}
<div>
    @Html.DisplayFor(model=>model.Id)
    @Html.DropDownListFor(model => model.Id, Model.PublisherList);
</div>
<div id="booksDiv">

</div>

我的模型code是

My model code is

using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace JsonRenderingMvcApplication.Models
{
    public class PublisherModel
    {
        public PublisherModel()
        {
            PublisherList = new List<SelectListItem>();
        }

        [Display(Name="Publisher")]
        public int Id { get; set; }
        public IEnumerable<SelectListItem> PublisherList { get; set; }
    }
}

我的实体code是

My entity code is

namespace JsonRenderingMvcApplication.DAL
{
    using System;
    using System.Collections.Generic;

    public partial class Publisher
    {
        public Publisher()
        {
            this.BOOKs = new HashSet<BOOK>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Year { get; set; }

        public virtual ICollection<BOOK> BOOKs { get; set; }
    }
}     

是这个实体有一个导航属性​​,但我不希望到实体数据,所以我不希望包括。

Yes this entity has a navigation property but I don't want to that entity data so I don't want to include that.

感谢

推荐答案

您遇到的问题是由于LINQ的延迟执行。它是谁尚未实现LINQ是如何工作的引擎盖下的开发商颇有疑难杂症。我有一个伟大的博客文章,但核心理念是,你必须迫使该集合的枚举以使LINQ code运行的,而不是立即之后。这意味着改变这个:

The problem you're experiencing is due to LINQ's deferred execution. It's quite the gotcha for developers who haven't yet realized how LINQ works under the hood. I have a great blog post about it, but the core concept is that you must force an enumeration on the collection to cause the LINQ code to run immediately instead of later. This means changing this:

model.PublisherList = context.Publishers.Select(x =>
    new SelectListItem()
    {
        Text = x.Name,
        Value = x.Id.ToString()
    });

这样:

model.PublisherList = context.Publishers.Select(x =>
    new SelectListItem()
    {
        Text = x.Name,
        Value = x.Id.ToString()
    }).ToList();

请注意在 .ToList()有哪些强制枚举。

Note the .ToList() there which forces the enumeration.

您LINQ查询的延迟这意味着它没有在您的控制器在视图上运行,而是事后,也许在这里你遍历集合(其中强制枚举,从而运行LINQ) 。因为你使用使用语句处置您的数据库环境(这当然是很好的做法),上下文布置到达视图,执行前code反对处置环境。强制使用语句中枚举运行当时的code,而不是后来当环境布置和prevent这个问题。

Your LINQ query is deferred meaning that it is not being run at your controller but instead afterwards, probably in your view where you loop over the collection (which forces the enumeration and thus runs the LINQ). Because you're using the using statement to dispose of your DB context (which is of course good practice), the context is disposed of before you reach the view, which executes the code against the disposed context. Forcing the enumeration within the using statement will run the code at that time, instead of later when the context is disposed, and prevent this issue.

这篇关于操作无法完成,因为的DbContext一直使用MVC 4处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆