我正在使用Asp.net核心Razor引擎實體框架。我不斷收到上面的錯誤以及我讀過的錯誤,它指的是已經用於操作的數據庫。我不知道爲什麼會發生這種情況。是因爲它處於foreach循環嗎?解決方法是什麼?這裏是我的代碼InvalidOperationException:操作已在進行中
[HttpGet]
[Route("currentSession")]
public IActionResult CurrentSession()
{
var id = HttpContext.Session.GetInt32("Id");
if(id != null)
{
var user = _context.User.FirstOrDefault(x => x.Id == id);
ViewBag.User = user;
ViewBag.User_Id = id;
ViewBag.Auction = _context.Auction.AsEnumerable();
foreach(var item in ViewBag.Auction)
{
if(item.End_Date < DateTime.Now)
{
var seller_id = (int)item.Id_Of_Seller;
var seller = _context.User.FirstOrDefault(x => x.Id == seller_id); //this is the line that causes the error in the title
var bidder_id = (int)item.Id_Highest_Bid;
var buyer = _context.User.FirstOrDefault(x => x.Id == bidder_id); //this line also causes the same error
buyer.Wallet -= item.Bid;
seller.Wallet += item.Bid;
_context.Auction.Remove(item);
_context.SaveChanges();
}
}
return View("Home");
}
return RedirectToAction("LoginPage");
}
謝謝,爲什麼這樣做? – Aaron
因爲枚舉不會加載內存中的所有數據,而是在您通過_context枚舉數據時從數據庫中提取數據,並且在循環內您再次使用_context刪除正在枚舉的同一實體上的數據。調用.ToList()會首先加載拍賣數據的副本,因此_context只能在拍賣實體上執行單一操作,即移除。 – vendettamit
AsEnumerable是一個延遲動作,並且你正在該步驟中的db上下文上再次執行某些操作。這就是你遇到這個錯誤的原因。 – Teja