2016-02-12 43 views
0

,我發現了異常:的EntityFramework ObjectContext的實例已經被設置在某個位置

「的ObjectContext的實例已經設置,不能再用於需要連接的操作」

只有當我嘗試將該對象或該對象的某些屬性添加到@Html.ActionLink

我已經檢查了幾次我的代碼,找不到任何異常對可能導致此異常的任何建議?

謝謝!

UserManagerResult.cs

public class UserManagerResult { 
    public bool Success{get; set;} 
    public string ErrorMessage{get; set;} 
    public Account User{get; set;} 
    public List <Account> UserList{get;} 
    public UserManagerResult() { 
     Success = false; 
     UserList = new List <Account>(); 
    } 

} 

UserManager.cs

public static UserManagerResult GetUserList() { 
     UserManagerResult userManagerResult = new UserManagerResult(); 
     try { 
      using (AlenMotorsDbEntities alenMotorsDbEntities = new AlenMotorsDbEntities()) { 
       foreach (Account account in alenMotorsDbEntities.Accounts.ToList()) { 
        userManagerResult.UserList.Add(account); 
       } 
       return userManagerResult; 
      } 
     } 
     catch (Exception ex) { 
      userManagerResult.ErrorMessage = ex.Message; 
      return userManagerResult; 
     } 
    } 

DeveloperViewModel.cs

public class DeveloperViewModel { 
    [Display(Name = "New Role")] 
    public string NewRole{get; set;} 
    [Display(Name = "Remove Role")] 
    public List <SelectListItem> RoleList{get; set;} 
    [Display(Name = "User list")] 
    public List <Account> UserList{get; set;} 
} 

個UserManagerController.cs

public ActionResult Developer(DeveloperViewModel model) { 
     UserManagerResult getUserList = UserManager.GetUserList(); 
     model.UserList = getUserList.UserList.ToList(); 
     return View(model); 
    } 

的觀點我使用

    @{ 
       foreach (Account account in Model.UserList.ToList()) { 
        <tr> 
         <th scope="row">--</th> 
         <td>@account.Email</td> 
         <td>@account.LastName</td> 
         <td>@account.FirstName</td> 
         <td> 
          @Html.ActionLink("Remove", "Remove", account) 
         </td> 
        </tr> 
       } 
      } 
+0

讓我看看您的賬戶實體。這可能是懶惰的加載操作。將'userManagerResult.UserList.Add(account);'中的'account'轉換爲一些投影 –

+0

我已經通過將需要的信息從Account轉移到一個新類AccountViewModel來解決問題,只顯示相關信息。 – alentor

回答

0

在你GetUserList(),試試這個:

foreach (Account account in alenMotorsDbEntities.Accounts.Include(i=>i.YourOtherEntity).Include(i=>i.AnotherEntity).ToList()) 

而且不斷加入所有相關實體是相關的。

+0

我試過使用包括但我沒有包含什麼..因爲我想整個alenMotorsDbEntities.Accounts到列表 http://tiny.cc/36628x – alentor

相關問題