How to update records from IList in Foreach loop?

My controller goes through a list, which I then need to skip and update every entry in the list in my database. I am using ASP.NET MVC with a repository pattern using Linq to Sql. The code below is my save method, which should add an entry to the table of accounts, and then update the corresponding tasks in the table of tasks from db.

public void SaveInvoice(Invoice invoice, IList<InvoiceJob> invoiceJobs) { invoiceTable.InsertOnSubmit(invoice); invoiceTable.Context.SubmitChanges(); foreach (InvoiceJob j in invoiceJobs) { var jobUpdate = invoiceJobTable.Where(x => x.JobID == j.JobID).Single(); jobUpdate.InvoiceRef = invoice.InvoiceID.ToString(); invoiceJobTable.GetOriginalEntityState(jobUpdate); invoiceJobTable.Context.Refresh(RefreshMode.KeepCurrentValues, jobUpdate); invoiceJobTable.Context.SubmitChanges(); } } 

** I deleted the code only in the problem area.

This code does not work, and work records are not updated, but the table of accounts is updated perfectly. No errors occur, and invoiceJobs IList is definitely not null. If I change the code by deleting the foreach loop and manually specifying which JobId will be updated, it works fine. The following works:

 public void SaveInvoice(Invoice invoice, IList<InvoiceJob> invoiceJobs) { invoiceTable.InsertOnSubmit(invoice); invoiceTable.Context.SubmitChanges(); var jobUpdate = invoiceJobTable.Where(x => x.JobID == 10000).Single(); jobUpdate.InvoiceRef = invoice.InvoiceID.ToString(); invoiceJobTable.GetOriginalEntityState(jobUpdate); invoiceJobTable.Context.Refresh(RefreshMode.KeepCurrentValues, jobUpdate); invoiceJobTable.Context.SubmitChanges(); } 

I just can't get the foreach loop to work at all. Does anyone know what I'm doing wrong here?

+4
source share
2 answers

It seems that the most likely cause of this problem is that the invokeJobs collection is an empty collection. That is, it has no elements, so the foreach does nothing effectively.

You can verify this by adding the following to the top of the method (for debugging purposes only)

 if (invoiceJobs.Count == 0) { throw new ArgumentException("It an empty list"); } 
+1
source

Change it

  var jobUpdate = invoiceJobTable.Where(x => x.JobID == 10000).Single(); jobUpdate.InvoiceRef = invoice.InvoiceID.ToString(); invoiceJobTable.GetOriginalEntityState(jobUpdate); invoiceJobTable.Context.Refresh(RefreshMode.KeepCurrentValues, jobUpdate); invoiceJobTable.Context.SubmitChanges(); 

to

  var jobUpdate = invoiceJobTable.Where(x => x.JobID == 10000).Single(); jobUpdate.InvoiceRef = invoice.InvoiceID.ToString(); invoiceJobTable.SubmitChanges(); 

It looks like your GetOriginalEntityState actually doing nothing, because you are not using the return value. I see no reason why you are calling the DataContext.Refresh() call. All he does is erase your changes, thereby making the foreach loop inoperative.

0
source

Source: https://habr.com/ru/post/1346281/


All Articles