9

我正在 EF 4.1 中编写一个简单的应用程序,它将使用我的公共数据源(数据库中央服务器)的添加、删除、编辑和详细信息。在我的控制器类中,我写道:

    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);
       }

    }
}

当我执行我的应用程序时,它在 foreach 语句的索引视图中给了我一个错误:

@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>

错误是这样的:“操作无法完成,因为 DbContext 已被释放。”

4

2 回答 2

15

您应该使用 List 作为模型传递

我假设 db.Registrant 返回用户列表?如果是这样,请执行以下操作

List<Registrant> items = null;

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

return View(items);
于 2012-08-08T07:15:52.590 回答
6

只是为了进一步评论,您需要区分您的担忧。您不应该在控制器中使用这样的数据库上下文。而是通过存储库或服务层使用它。

我在使用时也遇到了这个问题using。我删除了使用部分。修改下面的代码以适应您的场景。假设您要带回用户列表。我会在我的存储库类中有这个:

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

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

然后,您通过 Autofac、Ninject 等将这个存储库注入到您的控制器中。

在您的控制器中,它看起来像这样:

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()
          };
     }
}

然后在您看来,您可以遍历用户。

于 2012-08-08T09:45:28.023 回答