6

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();
2
  • 2
    The code you provide will update all elements in ClientDebtList, you migth want to add a if null check before setting debt.Active =.... Commented Nov 16, 2016 at 13:24
  • 1
    Or atleast all touched elements will be updated in the database. Commented Nov 16, 2016 at 13:25

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.