我在EF 4.1中编写了一个简单的应用程序,它将使用我的公共数据源(数据库的中央服务器)添加,删除,编辑和详细信息。 在我的Controller类中,我写道:
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,因此无法完成操作。”
答案 0 :(得分:14)
您应该使用List作为模型传递
我假设db.Registrant返回一个用户列表?,如果有的话,这样做
List<Registrant> items = null;
using (var db = new RegModelContext(CmdStr))
{
items = db.Registrant.ToList();
}
return View(items);
答案 1 :(得分: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()
};
}
}
然后在您的视图中,您可以循环访问用户。