Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The operation cannot be completed because the DbContext has been disposed

I am writing a simple application in EF 4.1 which will use add, delete , edit and detail form my common data source (central server for 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 am executing my Application it gave me an error in index view at 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>

The error is this: "The operation cannot be completed because the DbContext has been disposed."

like image 770
Fahad Mahmood Avatar asked Aug 08 '12 07:08

Fahad Mahmood


People also ask

Does dbContext need to be disposed?

As Daniel mentioned, you don't have to dispose the dbContext. From the article: Even though it does implement IDisposable, it only implements it so you can call Dispose as a safeguard in some special cases. By default DbContext automatically manages the connection for you.


2 Answers

You should use a List to pass as your model

i assume that db.Registrant return a list of users?, if so do something like this

List<Registrant> items = null;

using (var db = new RegModelContext(CmdStr))
{
    items = db.Registrant.ToList();
}

return View(items);
like image 138
JohnnBlade Avatar answered Oct 13 '22 01:10

JohnnBlade


Just to comment further, you need to separate your concerns. You shouldn't use the database context like that in a controller. Rather use it through a repository or service layer.

I also had this issue when using using. I removed the using part. Modify the code below to fit in with your scenario. Assuming you are to bring back a list of users. I would have this in my repository class:

public class UserRepository : IUserRepository
{
     MyDbContext dbContext = new MyDbContext();

     public IEnumerable<User> GetAll()
     {
          return dbContext.Users;
     }
}

This repository you then have injected in your controller by Autofac, Ninject, etc.

In your controller it would 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 view you can just loop through the users.

like image 24
Brendan Vogt Avatar answered Oct 12 '22 23:10

Brendan Vogt