的EntityFramework ObjectContext的实例已经被设置在某个位置

问题描述:

,我发现了异常:的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

在你GetUserList(),试试这个:

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

而且不断加入所有相关实体是相关的。

+0

我试过使用包括但我没有包含什么..因为我想整个alenMotorsDbEntities.Accounts到列表 http://tiny.cc/36628x – alentor