Reputation: 663
Would 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;
}
Data.Generic.SaveChanges();
Upvotes: 6
Views: 2343
Reputation: 65870
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.
Upvotes: 4
Reputation: 81
the changes to entities are monitored internally, therefore none of your changes should be lost as long as you did not tell the entity framework to skip the change tracking (e.g. using AsNotracking()
in your query)
Upvotes: 2