We are using Entity Framework Code First, and I am running into issues trying to rollback entity changes for Insert, Update, and Delete when we don't want to SaveChanges()
.
Specifically, I have a datagridview which I am using as a TableEditor, to make changes to some auxiliary tables. The datagridview is bound to DbSet<TEntity>
.
My rollback for Update seems to work fine, I just set the currentValues to back to their OriginalValues, and change state to unchanged
.
When a record is inserted to the gridview (but no changes saved), it never shows up in the entity class, and I never see it again... So I guess it doesn't make it to the dbSet, and no rollback is needed for this?
But my main problem lies with Delete:
From what I understand, when a record is "deleted" (eg.tableData.Remove(currentItem);
), it is simply marked for deletion until SaveChanges is called. So if I change the State from deleted
back to unchanged
, that should handle the rollback, right?
Well, the record does show back up again, BUT the navigational properties of the record are gone! (ie. the columns containing foreign keys and required relationships to other entities). Why is this??!
Here is what I have so far:
public void RollbackChanges(DbEntityEntry entry)
{
if (entry.State == EntityState.Modified)
{
foreach (var propertyName in entry.OriginalValues.PropertyNames)
{
entry.CurrentValues[propertyName] = entry.OriginalValues[propertyName];
}
entry.State = EntityState.Unchanged;
}
else if (entry.State == EntityState.Deleted)
{
entry.State = EntityState.Unchanged;
}
else if ((entry.State == EntityState.Added) || (entry.State == EntityState.Detached))
{
MessageBox.Show("I don't think this ever happens?");
}
}
Example usage:
foreach (var entity in db.CertificationDecisions)
{
DbEntityEntry entry = db.Entry(entity );
if (entry.State != EntityState.Unchanged)
{
RollbackChanges(entry);
}
}
Any ideas why the navigational properties would disappear from the record? (Or what I can do to get them back?)
EDIT: @Chris regarding using
Refresh
:
I am using a DbContext, so I replaced my rollback methods with this line:
((IObjectContextAdapter)db).ObjectContext.Refresh(RefreshMode.StoreWins, db.CertificationDecisions);
However, this does not seem to reload the context, as the record is still missing... Am I using Refresh
wrong?
This sounds like a possible solution to my problem, but I am still wondering why the navigation properties would be removed?