I developed a web application with ASP.NET MVC 4 and SQL Server 2008, I am creating a ContextManager class to have only one database context on 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 correctly on most pages, but something goes wrong on the registration page, and my context is reset with the following error:
The operation could not be completed because the DbContext was deleted.
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 );
in the line _db.Contacts.Add( contact ); I got an exception.
But without using ContextManager, changing
HotelContext _db = ContextManager.Current;
in
HotelContext _db = new HotelContext();
the problem is resolved. But I need to use my own ContextManager. What is the problem?
source share