我在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行我的应用程序时,它在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>
Run Code Online (Sandbox Code Playgroud)
错误是这样的:"由于已经处理了DbContext,因此无法完成操作."
Joh*_*ade 14
您应该使用List作为模型传递
我假设db.Registrant返回一个用户列表?,如果这样做的话
List<Registrant> items = null;
using (var db = new RegModelContext(CmdStr))
{
items = db.Registrant.ToList();
}
return View(items);
Run Code Online (Sandbox Code Playgroud)
只是为了进一步评论,您需要将您的疑虑分开.您不应该像控制器中那样使用数据库上下文.而是通过存储库或服务层使用它.
使用时我也遇到过这个问题using.我删除了使用部分.修改下面的代码以适应您的方案.假设您要带回一个用户列表.我会在我的存储库类中有这个:
public class UserRepository : IUserRepository
{
MyDbContext dbContext = new MyDbContext();
public IEnumerable<User> GetAll()
{
return dbContext.Users;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过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()
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您可以循环访问用户.
| 归档时间: |
|
| 查看次数: |
20530 次 |
| 最近记录: |