Reputation: 111
I'm currently developing an MVVM app using a Model-Designer based code-first design. So far I've been able to get all the basic CRUD operations working on single entities, however I can't seem to change the properties of collection objects at all using SaveChanges()
- I've used an SQL profiler to see that it's attempting to UPDATE with the old value, and a step right after SaveChanges()
my changes get reverted to their old values!
Some other info:
dbContext
is loaded using DI from PRISM/Unity and kept as a Unit-of-Work for a "details" page the user will edit and then save.Add()
to insert entities.Attach()
and AddOrUpdate()
on any or all items.Entry()
properties of IsModified
and CurrentValue to their desired settings.dbContext.Classes.Local.ToBindingList()
or new ObservableCollection<Class>(Entity.Property)
.Is there anything that I could be missing here? Here's one attempt I've tried: // Assigning an Index object that contains relationships Index = await _model.PersonIndexes.Include(i => i.PersonAddresses).FirstAsync(i => i.Id == IndexId);
// Grabbing a filtered set of Addresses based on their data
var query = Index.PersonAddresses.Where(e => e.Condition == true );
Addresses = new ObservableCollection<PersonAddress>(await query.ToListAsync());
// Ensure state is tracked (I've tried with and without all combinations of these)
foreach (PersonAddress addr in Addresses)
{
//_model.PersonAddresses.AddOrUpdate(a => a.Id, addr);
if (addr.PendingRemoval)
{
_model.PersonAddresses.Attach(addr);
_model.Entry(addr).Property(a => a.PendingRemoval).CurrentValue = true;
_model.Entry(addr).Property(a => a.PendingRemoval).IsModified = true;
}
}
// Saving (after this line the properties of the entities in the related collection get reverted to their old values - i.e. if I change a phone number in the UI, the save below will replace the new values with the previous number.
await _model.SaveChangesAsync();
Upvotes: 1
Views: 552
Reputation: 111
So it turns out this was an unfortunate error of configuration and a bad coincidence:
1) Check your models and server schema to ensure they are in sync (especially if using generated code from EF). In my case they were not, which lead to...
2) SaveChanges()
was overwriting my properties in question because I had not noticed they were incorrectly set to have their StoredGeneratorPattern
set to Computed
in my model code. This caused the changed values to be ignored and overwritten.
3) The test case surrounding this had only implemented the same properties that were marked incorrectly, making it appear that all changes were being reverted - causing the confusion on where the problem code actually was. If another column had been modified and watched along with the others, this might have been caught sooner.
Upvotes: 1