The operation could not be completed because the DbContext was deleted.

I am writing a simple application in EF 4.1 that will use the addition, deletion, editing and granularity of my shared data source (central server for the database). In my controller class, I write:

public class RegController : Controller { // // GET: /Reg/ private string CmdStr = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; public ActionResult Index() { using (var db = new RegModelContext(CmdStr)) { return View(db.Registrant); } } } 

when I execute my application, it gave me an error in representing the index in the foreach statement:

 @model IEnumerable<Registration.Models.Register> @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th></th> <th> UserName </th> <th> Password </th> <th> Email </th> <th> Address </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> <td> @item.UserName </td> <td> @item.Password </td> <td> @item.Email </td> <td> @item.Address </td> </tr> } </table> </body> </html> 

Error: "The operation could not be completed because the DbContext was deleted."

+7
source share
2 answers

You should use the transfer list as a model.

I assume db.Registrant returns a list of users? If so something like this

 List<Registrant> items = null; using (var db = new RegModelContext(CmdStr)) { items = db.Registrant.ToList(); } return View(items); 
+12
source

To comment further, you need to separate your concerns. You should not use a database context similar to this in the controller. Rather, use it through the repository or service level.

I also had a problem using using . I deleted the used part. Modify the code below to fit your scenario. Assuming you should return a list of users. I would do this in my repository class:

 public class UserRepository : IUserRepository { MyDbContext dbContext = new MyDbContext(); public IEnumerable<User> GetAll() { return dbContext.Users; } } 

This repository, which you then injected into your Autofac, Ninject controller, etc.

In your controller, it will look something like this:

 public class UserController : Controller { private readonly IUserRepository userRepository; public UserController(IUserRepository userRepository) { this.userRepository = userRepository; } public ActionResult Index() { UserViewModel viewModel = new UserViewModel { Users = userRepository.GetAll() }; } } 

And then, in your opinion, you can simply skip users.

+6
source

All Articles