![](/img/trans.png)
[英]The operation cannot be completed because the DbContext has been disposed in mvc
[英]The operation cannot be completed because the DbContext has been disposed using MVC 4
我知道這個問題被問過這么多次。 我已閱讀並實施了所有解決方案但未獲得成功。 當我使用EF從數據庫檢索數據並在View上使用此模型后與模型綁定時,我收到此錯誤。
我的控制器代碼是
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);
}
}
}
我的查看代碼是
@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>
我的型號代碼是
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; }
}
}
我的實體代碼是
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; }
}
}
是的,這個實體有一個導航屬性,但我不想要那個實體數據,所以我不想包含它。
謝謝
您遇到的問題是由於LINQ的延遲執行。 對於那些還沒有意識到LINQ如何工作的開發人員來說,這是非常困難的。 我有一篇很棒的博客文章,但核心概念是你必須強制對集合進行枚舉,以使LINQ代碼立即運行而不是以后運行。 這意味着改變這個:
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()
會強制枚舉。
您的LINQ查詢是延遲的 ,這意味着它不會在您的控制器上運行,而是在您的視圖中運行,可能在您的視圖中循環集合(這會強制枚舉並因此運行LINQ)。 因為您正在使用using
語句來處理您的數據庫上下文(這當然是一種很好的做法),所以在您到達視圖之前會先處理上下文,該視圖會針對已處置的上下文執行代碼。 在using
語句中強制枚舉將在那時運行代碼,而不是在處理上下文時運行代碼,並防止出現此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.