I am using Asp.net core Razor engine Entity Framework. I keep getting the error above and it from what I have read, it refers to the the db already being used for an operation. I am not sure why this would be happening. Is is because it is in a foreach loop? What would the workaround be? Here is my code
[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");
}
Can you try replacing AsEnumerable with ToList?
ViewBag.Auction = _context.Auction.ToList();