我开发了一个ASP.NET MVC 4和SQL Server 2008的Web应用程序,我创建了ContextManager类,在所有页面中只有一个数据库上下文。DbContext已经部署了
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;
}
}
}
它可以正常工作中大部分的网页,但在注册页面出现错误,我的背景下飘以下错误废黜:在该行_db.Contacts.Add(contact);
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);
我得到异常。
,但没有使用ContextManager通过改变
HotelContext _db = ContextManager.Current;
到:
HotelContext _db = new HotelContext();
的问题得到解决。但我需要使用我自己的ContextManager。问题是什么?
创建用户后,我也检查了我的数据库,确保WebSecurity.CreateUserAndAccount正在成功进行,但在_db.Contacts.Add(contact);我得到了例外。 –
@ ken2k,ContextManager正在HttpContext.Current.Items中存储DbContext,因此它将成为每个请求的新实例。 – mendel