我開發了一個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