DbContext has been removed

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?

+6
source share
4 answers

Your context was deleted somewhere else (and not in the code you specified), so basically when you access it from your Register action, it throws an exception.

In fact, you should not use a static singleton to access your context. Create an instance of a new DbContext instance for each request . See C # working with Entity Framework on a multi-threaded server

+8
source

You are probably lazily loading the User navigation property in your login view. Be sure to enable it using the Include method on your DbSet before sending it to the view:

 _db.Users.Include(u => u.PropertyToInclude); 

In addition, sharing a DbContext with a static property can have unexpected side effects.

+2
source

In my case, my GetAll method did not call the ToList () method after the where clause in the lambda expression. After using ToList (), my problem was resolved.

 Where(x => x.IsActive).ToList(); 
+2
source

I had the same problem. I decided to do this, as mentioned above. Create a new instance of your context.

Try using this:

  using (HotelContextProductStoreDB = new ProductStoreEntities()) { //your code } 

This way, every time you use your code, a new instance will be created and your context will not be deleted.

0
source

Source: https://habr.com/ru/post/953236/


All Articles