DbContext已被处置 [英] DbContext has been disposed
问题描述
我用ASP.NET MVC 4和SQL Server 2008开发了一个Web应用程序,我创建了ContextManager类,以便在所有页面中只有一个数据库上下文.
I developed a web application with ASP.NET MVC 4 and SQL Server 2008, I create ContextManager class to have only one database context in all pages.
public static class ContextManager
{
public static HotelContext Current
{
get
{
var key = "Hotel_" + HttpContext.Current.GetHashCode().ToString("x")
+ Thread.CurrentContext.ContextID.ToString();
var context = HttpContext.Current.Items[key] as HotelContext;
if (context == null)
{
context = new HotelContext();
HttpContext.Current.Items[key] = context;
}
return context;
}
}
}
它在大多数页面上都能正常工作,但是在注册页面上出现了问题,我的上下文被以下错误所取代:
It works properly in most of the pages, but in registration page something goes wrong and my context gone deposed with following error:
由于已处理DbContext,因此无法完成该操作.
The operation cannot be completed because the DbContext has been disposed.
public ActionResult Register ( RegisterModel model )
{
if ( ModelState.IsValid )
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount( model.UserName, model.Password,
new
{
Email = model.Email,
IsActive = true,
Contact_Id = Contact.Unknown.Id
} );
//Add Contact for this User.
var contact = new Contact { Firstname = model.FirstName, LastName = model.Lastname };
_db.Contacts.Add( contact );
var user = _db.Users.First( u => u.Username == model.UserName );
user.Contact = contact;
_db.SaveChanges();
WebSecurity.Login( model.UserName, model.Password );
在行_db.Contacts.Add( contact );
处出现了异常.
但无需通过更改使用ContextManager
But without using ContextManager by changing
HotelContext _db = ContextManager.Current;
进入:
HotelContext _db = new HotelContext();
问题已解决.但是我需要使用自己的ContextManager.有什么问题吗?
the problem was solved. But I need to use my own ContextManager. What is the problem?
推荐答案
您的上下文已放置在其他地方(不在您显示的代码中),因此,基本上,当您从Register
动作访问它时,它会抛出例外.
Your context has been disposed somewhere else (not in the code you've shown), so basically when you access it from your Register
action, it throws the exception.
实际上,您不应使用静态单例来访问上下文. 为每个请求实例化一个新的DbContext
实例.请参阅使用Entity Framework的c#在多线程服务器中
Actually, you shouldn't use a static singleton to access to your context. Do instantiate a new DbContext
instance for each request. See c# working with Entity Framework in a multi threaded server
这篇关于DbContext已被处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!