I'm developing an app in C# that needs to update some entries on an existing database. I'm using Linq.
Ok, so, I have this User with its properties (Id, Name, City, ToUpdate, ToInsert, IsActive, IdUserUpdate and so on).
My app has a foreach, and inside I'm editing an existing registry on my database for each iteration.
It goes like this:
myList.ForEach(X => {
var oldRegistry = database.MyTable.FirstOrDefault(Y => Y.Id == X.Id);
oldRegistry.City = X.City;
oldRegistry.IdUserUpdate = -3;
oldRegistry.ToUpdate = false;
oldRegistry.ToInsert = true;
oldRegistry......................
database.SaveChanges();
});
The problem is that from the second iteration on, the oldRegistry does not get its ToUpdate and ToInsert fields updated (both bit in the database).
I've tested almost everything, and nothing... If I add a breakpoint on that savechanges, I can scan my oldRegistry properties that are about to be saved to the database, and everything is like it should, but when I check the database after the SaveChanges, not all the fields are updated (IdUserUpdated is updated, but ToUpdate and ToInsert are not).
I've tried reloading the database's entities but since my foreach has 2000 iterations everytime, it takes a ridiculous amount of time to clear them (10 entities per iteration). The code for this is the following:
foreach (var entity in database.ChangeTracker.Entries())
{
entity.Reload();
}