简体   繁体   English

由于已使用MVC 4处理了DbContext,因此无法完成操作

[英]The operation cannot be completed because the DbContext has been disposed using MVC 4

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. 当我使用EF从数据库检索数据并在View上使用此模型后与模型绑定时,我收到此错误。

My controller code is 我的控制器代码是

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);
        }

    }
}

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>

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; }
    }
}

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. 是的,这个实体有一个导航属性,但我不想要那个实体数据,所以我不想包含它。

Thanks 谢谢

The problem you're experiencing is due to LINQ's deferred execution. 您遇到的问题是由于LINQ的延迟执行。 It's quite the gotcha for developers who haven't yet realized how LINQ works under the hood. 对于那些还没有意识到LINQ如何工作的开发人员来说,这是非常困难的。 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. 我有一篇很棒的博客文章,但核心概念是你必须强制对集合进行枚举,以使LINQ代码立即运行而不是以后运行。 This means changing this: 这意味着改变这个:

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

to this: 对此:

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

Note the .ToList() there which forces the enumeration. 注意.ToList()会强制枚举。

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). 您的LINQ查询是延迟的 ,这意味着它不会在您的控制器上运行,而是在您的视图中运行,可能在您的视图中循环集合(这会强制枚举并因此运行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. 因为您正在使用using语句来处理您的数据库上下文(这当然是一种很好的做法),所以在您到达视图之前会先处理上下文,该视图会针对已处置的上下文执行代码。 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. using语句中强制枚举将在那时运行代码,而不是在处理上下文时运行代码,并防止出现此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 操作无法完成,因为 DbContext 已在 mvc 中处置 - The operation cannot be completed because the DbContext has been disposed in mvc “操作无法完成,因为 DbContext 已被释放。” - 'The operation cannot be completed because the DbContext has been disposed.' 由于已经处理了DbContext,因此无法完成操作 - The operation cannot be completed because the DbContext has been disposed 由于 DbContext 已在 Web API 中配置,操作无法完成 - The operation cannot be completed because the DbContext has been disposed in Web API 错误“操作无法完成,因为 DbContext 已被释放。” - Error "The operation cannot be completed because the DbContext has been disposed." 由于DbContext已被处置错误,因此无法完成该操作 - The operation cannot be completed because the DbContext has been disposed error 该操作无法完成,因为DbContext已被处置 - The operation cannot be completed because the DbContext has been disposed exception 该操作无法完成,因为已经丢弃了DbContext。” - operation cannot be completed because the DbContext has been disposed." 由于已处置DbContext,因此无法完成该操作 - The operation cannot be completed because the DbContext has been disposed EF6由于已经处理了DbContext,因此无法完成操作 - EF6 The operation cannot be completed because the DbContext has been disposed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM