Ok so I am stumped on how to achieve this. I have a database entity framework table called "ProductOrders" that saves a new record when a new order is placed. What I want to do though is after it saves the new record, I want to get the value of the "Qty Available" field that was just created/saved and then loop through all the records in the table and if there are any records where the "ProductID" field is the same as the one that was just created, then I want to change the value of the "Qty Available" field to the new "Qty Available" value from the newest entry. An example would be if someone ordered product # ABC on order # 100 and the new Qty Available value was 10 for that product. After that record is created, I want it to check every record in that table to see if there are other orders containing product # ABC. If there is, then change the Qty Available value to 10 for each one. I tried this and it didn’t work:
productOrder = db.ProductOrders.Find(id);
foreach (var item in db.ProductOrders.Where(x => x.ProductID == productOrder.ProductID))
{
item.Qty_Available = productOrder.Qty_Available;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
I got the error message: "New transaction not allowed because there are other threads running in the session". I just can’t seem to get this to work. I’m not sure if I need to do a foreach statement or if I’m on the wrong track, right track…I would greatly appreciate any help as I have been stuck on this for days.
2
Answers
Oh wow, I feel really stupid now. I simply added .ToList() at the end of the for each statement and it worked lol.
It looks like you’re better off creating another table called
productAvailableQuantity
that has aproductID
,Description
andQuantity
. That way when you’re saving a new record to theproductOrder
table you can just update theproductAvailableQuantity
table without having to loop through all the records inproductOrder
table.