私はAsp.netコアRazorエンジンEntity Frameworkを使用しています。私は上記のエラーを取得し続け、私が読んだことから、それは操作のために既に使用されているdbを指しています。なぜこれが起こっているのか分かりません。それは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
enumerablesはメモリ内のすべてのデータを読み込むのではなく、_context経由で列挙し、_contextを再度使用してループ内で列挙する同じエンティティのデータを削除するときに、DBからデータをフェッチします。 .ToList()を呼び出すと、最初にAuctionデータのコピーがロードされます。したがって、_contextは、Auctionエンティティに対して実行する操作は1つだけです。つまり、Removeです。 – vendettamit
AsEnumerableは遅延アクションであり、そのステップでdbコンテキストで何かを再度実行しています。それがあなたがそのエラーに遭遇した理由です。 – Teja