Entityframework ObjectContext instance has been disposed in certain location

297 Views Asked by At

I'm getting the exception:

"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

Only when I try to add the object or some properties of that object to @Html.ActionLink.

I have reviewed my code couple of times and can't find anything unusual any suggestions on what might be causing this exception?

Thank you!

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

The view I'm using

                 @{
                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>
                }
            }
1

There are 1 best solutions below

1
On

In your GetUserList(), try this:

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

And keep adding all related entities that is relevant.