I have a webpage with a form that is used to edit some object. This object contains a Collection of other objects defined like this:
Public Overridable Property Employees As List(Of Employee)
On a form I can delete an employee, add a new one or modify existing one. When I click save new values are sent to the server. On a server I check if the user exists. If exists then I modify its values, if it does not exist then I add it. All employees that exist on the server and were not sent are marked as deleted (State changed to EntityState.Deleted). I try to use the following code (dbCollection = database entities, newCollection = collection sent from the form):
For Each item In dbCollection
Dim dbItem = item
Dim newTask = newCollection.FirstOrDefault(Function(i) i.Id = dbItem.Id)
If newTask Is Nothing Then
Me.Entry(item).State = EntityState.Deleted
Else
Me.Entry(item).CurrentValues.SetValues(newTask)
newCollection.Remove(newTask)
End If
Next
For Each item In newCollection
dbCollection.Add(item)
Next
Me.SaveChanges()
This code does not work, because changing to EntityState.Deleted removes the object from collection, and for each loop breaks, since the collection is modified…
I know that I can overcome this problem by using a for loop or adding objects to delete to some other list first, but I hope maybe there is a pattern that would make my code nicer.
Thanks in advance for all suggestions.
Replace…
…by:
ToList()will create a copy of the collection (only the references, not the objects themselves).dbCollection.ToList()is another collection thandbCollectionso that you safely can modify thedbCollectionwithout getting the “collection has been modified” exception in theFor Eachloop.