C# Entityframework ObjectContext实例已在特定位置释放
我得到了一个例外: “ObjectContext实例已被释放,不能再用于需要连接的操作。” 仅当我尝试将对象或该对象的某些属性添加到C# Entityframework ObjectContext实例已在特定位置释放,c#,asp.net-mvc,entity-framework,objectdisposedexception,C#,Asp.net Mvc,Entity Framework,Objectdisposedexception,我得到了一个例外: “ObjectContext实例已被释放,不能再用于需要连接的操作。” 仅当我尝试将对象或该对象的某些属性添加到@Html.ActionLink时 我已经检查了我的代码好几次,没有发现任何不寻常的地方。关于什么可能导致这个异常的任何建议 谢谢大家! UserManagerResult.cs DeveloperViewModel.cs 我正在使用的视图 @{ foreach(Model.UserList.ToList()中的帐户){ -- @帐户。电子邮件 @account.L
@Html.ActionLink
时
我已经检查了我的代码好几次,没有发现任何不寻常的地方。关于什么可能导致这个异常的任何建议
谢谢大家!
UserManagerResult.cs
DeveloperViewModel.cs
我正在使用的视图
@{
foreach(Model.UserList.ToList()中的帐户){
--
@帐户。电子邮件
@account.LastName
@帐户名
@ActionLink(“删除”、“删除”、帐户)
}
}
在GetUserList()中,尝试以下操作:
foreach (Account account in alenMotorsDbEntities.Accounts.Include(i=>i.YourOtherEntity).Include(i=>i.AnotherEntity).ToList())
并不断添加所有相关的实体。我尝试过使用include,但没有要包含的内容。。因为我想让整个AlenMotorsBenties.Accounts列表显示您的帐户实体。这可能是延迟加载的结果。在
userManagerResult.UserList.Add(帐户)中转换您的帐户
代码>到某些项目我已经通过将所需信息从Account投影到一个新的类AccountViewModel来解决这个问题,以便只公开视图中的相关信息。
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;
}
}
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;}
}
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>
}
}
foreach (Account account in alenMotorsDbEntities.Accounts.Include(i=>i.YourOtherEntity).Include(i=>i.AnotherEntity).ToList())