Estoy escribiendo una aplicación simple en EF 4.1 que usará agregar, eliminar, editar y detallar mi fuente de datos común (servidor central para la base de datos). En mi clase controlador que escribo:La operación no se puede completar porque se ha eliminado el DbContext
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);
}
}
}
cuando estoy cumpliendo mi solicitud me dio un error en la vista del índice de instrucción 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>
El error es la siguiente: "La operación no puede se complete porque el DbContext ha sido eliminado ".
Debe devolver db.Registrant.ToList(), porque intenta ejecutar la consulta después de que se elimine el contexto de datos, ToList() obligará a ejecutarlo antes. – Giedrius