由于已经处理了DbContext,因此无法完成操作
我在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 @{ Layout = null; } Index @Html.ActionLink("Create New", "Create")
UserName Password Email Address @foreach (var item in Model) { @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) @item.UserName @item.Password @item.Email @item.Address }
错误是这样的:“由于已经处理了DbContext,因此无法完成操作。”
您应该使用List作为模型传递
我假设db.Registrant返回用户列表?,如果是这样的话
List items = null; using (var db = new RegModelContext(CmdStr)) { items = db.Registrant.ToList(); } return View(items);
只是为了进一步评论,您需要将您的疑虑分开。 您不应该像控制器中那样使用数据库上下文。 而是通过存储库或服务层使用它。
使用时我也遇到过这个问题。 我删除了使用部分。 修改下面的代码以适应您的方案。 假设您要恢复用户列表。 我会在我的存储库类中有这个:
public class UserRepository : IUserRepository { MyDbContext dbContext = new MyDbContext(); public IEnumerable 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() }; } }
然后在您的视图中,您可以循环访问用户。