2012-08-08 90 views
7

我正在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已經被處理完畢。「

+7

你需要返回db.Registrant.ToList(),因爲它試圖在datacontext被處理後執行查詢,ToList()將強制更早執行它。 – Giedrius 2012-08-08 07:14:10

回答

12

你應該用一個列表來傳遞的模型

我認爲db.Registrant返回用戶的列表?如果是的話做這樣的事情

List<Registrant> items = null; 

using (var db = new RegModelContext(CmdStr)) 
{ 
    items = db.Registrant.ToList(); 
} 

return View(items); 
+0

這一次,它給items = db.Registrant.ToList();該「 」執行命令定義時發生錯誤。 「 – 2012-08-08 07:24:07

+0

我改變了代碼,你是否試過這種方式? – JohnnBlade 2012-08-08 07:26:59

+3

爲什麼'從你...選擇你而不僅僅是'db.Registrant.ToList()' – sloth 2012-08-08 07:40:20

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() 
      }; 
    } 
} 

然後在您的視圖中,您可以循環訪問用戶。

+4

可能是因爲這對於實際問題來說是多餘的,它可能不應該是真的被低估了,但同時也不應該出於同樣的原因進行投票。需要遵守SoC,特別是如果它非常簡單 – 2013-07-02 12:27:34

相關問題