I expanded the class to add the last modified timestamp to the record if significant changes were made to it. This was done with code like this .
Here is my problem. SaveChanges()it starts for both changes, but the second does not fall into the loop: no object is detected as in need of changes.
However, the record is updated by EF through a call to base.SaveChanges ().
Here's an addendum to MasterTable:
namespace AuditTestEF
{
public interface IHasAuditing
{
DateTime LastModifiedOn { get; set; }
int LastModifiedBy { get; set; }
}
public partial class MasterTable : IHasAuditing
{
}
public class AuditTestEntitiesWithAuditing : AuditTestEntities
{
public int TestingUserIs = 1;
public override int SaveChanges()
{
foreach (ObjectStateEntry entry in (this as IObjectContextAdapter)
.ObjectContext
.ObjectStateManager
.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (entry.IsRelationship) continue;
var lastModified = entry.Entity as IHasAuditing;
if (lastModified == null) continue;
lastModified.LastModifiedOn = DateTime.UtcNow;
lastModified.LastModifiedBy = TestingUserIs;
}
return base.SaveChanges();
}
}
}
And here is the test harness:
[TestMethod]
public void TestMethod1()
{
MasterTable mtOriginal;
using (var audit = new AuditTestEntitiesWithAuditing())
{
var message = "Hello";
audit.TestingUserIs = 1;
mtOriginal = new MasterTable {TextField = message};
audit.MasterTable.Add(mtOriginal);
audit.SaveChanges();
Assert.IsTrue(mtOriginal.LastModifiedBy == audit.TestingUserIs);
}
using (var audit = new AuditTestEntitiesWithAuditing())
{
var mt = audit.MasterTable.Find(mtOriginal.MasterTableId);
mt.TextField = "Goodbye";
audit.TestingUserIs = 4;
audit.SaveChanges();
Assert.IsTrue(mt.LastModifiedBy == audit.TestingUserIs);
}
}
There is no other code. There is no weird disconnecting / tracking entity or anything else. WYSIWYG.
What am I missing? How is an explicitly modified object checked for Modified cleared?