DanielGatti DanielGatti - 1 year ago 89
C# Question

Entity Framework - Loop then call SaveChanges


save all changes of debt? Or only the last because it lost the reference because I change element debt in each loop?

List<DTO.ClientDebt> ClientDebtList = Business.Generic.GetAll<DTO.ClientDebt>();

foreach (var oClienteDeuda in oClienteDeudaSyncList) //oClienteDeudaSyncList is a list of debts
DTO.ClientDebt debt = ClientDebtList.Where(x => x.ClienteId == oClienteDeuda.ClienteId && x.NumeroComprobante == oClienteDeuda.NumeroComprobante).FirstOrDefault();
debt.Active = oClienteDeuda.Active ? 1 : 0;


Answer Source

The way you have done is the correct way when we're dealing with the foreach loops.You can do the same thing inside the loop too.But it'll degrade the performance of the operation heavily.So always do the SaveChanges() after the foreach loop.SaveChanges() method persist modifications made to all entities attached to it.So you don't need to worry about the reference changes and etc.It works as unit of work.That means either save all or none.

Note : SaveChanges() operates within a transaction. SaveChanges() will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download