I’ve several services using Entity Framework to save many changes in a DataBase.
When they’re executed in the IIS it goes really quick but when I’m in debug mode and running it on my development computer it takes a couple of minutes and I’ve see that all the rest queries crash (even if they are not over the same table I’m updating).
So I’ve thought I’m not doing this the way I should 😎
My code is something like this:
public void CancelOrders(ObservableCollection<long> idOrders)
{
Model.Entities context = new Model.Entities();
var query = from orders in context.ORDERS.Include("CUSTOMERS")
where idOrders.Contains(orders.id_order)
select orders;
foreach (var order in query)
{
foreach (var customer in order.CUSTOMERS)
{
customer.served = false;
}
context.ORDERS.DeleteObject(order);
}
context.SaveChanges();
}
The problems come when it runs the context.SaveChanges()… it use to be around 2000 rows and it takes a while to finish (and meanwhile NOBODY can use the same database).
Should I make a more frecuent context.SaveChanges()??? May I use a different approach??
Thanks in advance.
If you don’t need your deletes to be transasctional, then you can just call
SaveChanges()more frequently by adding it to the end of either the outerforeachloop or both the inner and the outer.I would suspect that you would at least want deleting an order and updating the customers to be transactional, so I would suggest only putting it within the outer
foreachloop.