,我發現了異常:的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>
}
}
讓我看看您的賬戶實體。這可能是懶惰的加載操作。將'userManagerResult.UserList.Add(account);'中的'account'轉換爲一些投影 –
我已經通過將需要的信息從Account轉移到一個新類AccountViewModel來解決問題,只顯示相關信息。 – alentor