I have a MVC application that used Entity Framework v6.0. Whenever a change is made to the DbContext
, I override the SaveChanges()
method and record the modifications in an audit log. Below is code for part of the audit log recording process:
public override int SaveChanges()
{
var ChangesEntities = ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted
|| e.State == EntityState.Modified
|| e.State == EntityState.Added).ToList();
foreach (DbEntityEntry entry in ChangesEntities)
{
if (entry.State == EntityState.Modified)
{
SetCorrectOriginalValues(entry);
}
...
}
...
return base.SaveChanges();
}
void SetCorrectOriginalValues(DbEntityEntry Modified)
{
var values = Modified.CurrentValues.Clone();
Modified.Reload();
Modified.CurrentValues.SetValues(values);
Modified.State = EntityState.Modified;
}
This code usually works, however, when I attempt to make a specific update, I am getting the following error:
Exception Message:
Member 'CurrentValues' cannot be called for the entity of type 'MyTable' because the
entity does not exist in the context.
To add an entity to the context call the Add or Attach method of DbSet.
Exception Stack Track:
at System.Data.Entity.Internal.InternalEntityEntry.get_CurrentValues()
at System.Data.Entity.Infrastructure.DbEntityEntry.get_CurrentValues()
at MyDatabaseName.DataLibrary.MyDatabaseEntities
.SetCorrectOriginalValues(DbEntityEntry Modified)
at MyDatabaseName.DataLibrary.MyDatabaseEntities.SaveChanges()
...
What does the exception message mean? When and why would CurrentValues
not be able to be called? What does is mean that entity does not exist in the context?
In MyDatabaseEntities.Context.cs, which extends DbContext
, 'MyTable' seems to exist:
public virtual DbSet<MyTable> MyTables { get; set; }
I checked the Entity Framework model diagram, and 'MyTable' exists there to.
base.SaveChanges()
is called, and that never seems to be a problem. Is that what you are referring to?