我正在EF 4.1中編寫一個簡單的應用程序,它將使用我的公共數據源(數據庫的中央服務器)的添加,刪除,編輯和詳細信息。 在我的控制器類我寫:操作無法完成,因爲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);
}
}
}
當我執行我的應用它給了我在索引視圖錯誤在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已經被處理完畢。「
你需要返回db.Registrant.ToList(),因爲它試圖在datacontext被處理後執行查詢,ToList()將強制更早執行它。 – Giedrius 2012-08-08 07:14:10