c# - Entity Framework 6 SaveChanges() override not consistently detecting changes -
i've extended class in order add last modified timestamp record if there material changes being made it. done code similar this.
here's problem. savechanges()
firing both changes, second 1 isn't getting loop: no objects detected needing changes.
however, record does updated ef through base.savechanges() call.
here's extension 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 iobjectcontextadapter) .objectcontext .objectstatemanager .getobjectstateentries(entitystate.added | entitystate.modified)) { // loop entered first time, not second if (entry.isrelationship) continue; var lastmodified = entry.entity ihasauditing; if (lastmodified == null) continue; lastmodified.lastmodifiedon = datetime.utcnow; lastmodified.lastmodifiedby = testinguseris; } return base.savechanges(); } } }
and here's 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(); // test passes, testinguser set in override 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(); // test fails, record written "goodbye" // getobjectstateentries(entitystate.added | entitystate.modified) has no entries. assert.istrue(mt.lastmodifiedby == audit.testinguseris); } }
there's no other code. there's no weird turning off/on entity tracking or anything. wysiwyg.
what missing? how modified object being missed check modified?
annnd... answered own question, of course, after talking duck.
public override int savechanges() { changetracker.detectchanges();
this fixes everything. thank attention, hope helps else.
Comments
Post a Comment