c# - EntityState clarification with SaveChanges -
i used technique shows in answer ( https://stackoverflow.com/a/6282472/2045385 ) create trackingdbcontext inherit many of contexts now, , entity needs createdate/lastmodified properties inherits trackingbase entity. has worked far.
until today.
ultimately fixed problem changing way add new entity collection, don't understand why original isn't working... , i'd understand figure going come bite me again , again until understand it.
originally adding new status record orderitem creating new status object , adding collection of statusitems of order object, so.
var newlypaidorders = shopdb.shoporders .where(o => o.status == "new" && o.payment >= o.cost) .tolist(); (int = 0; i< newlypaidorders.count; i++) { var paidorder = newlypaidorders.elementat(i); foreach ( var paiditem in paidorder.orderitems ) { shoporderitemstatus sois = new shoporderitemstatus { status = "paid", agent = "cronjob", shoporderitem = paiditem, comment = "" }; paiditem.shopitemorderstatus.add(sois); } paidorder.status = "paid"; } if (newlypaidorders.count > 0) shopdb.savechanges();
after savechanges() can see new status object created in database, but.... hey! createdate/lastmodified not updated, both null. put in breakpoints trackingdbcontext.savechanges() , sure enough, filter searching entities modified or added coming empty. whoah.. how can be?
ienumerable<objectstateentry> objectstateentries = e in context.objectstatemanager.getobjectstateentries(entitystate.added | entitystate.modified) e.isrelationship == false && e.entity != null && typeof(timestamptrackingbase).isassignablefrom(e.entity.gettype()) select e;
this morning got and, case, sleep gives new perspective. decided add item context.dbset directly rather modifying object had in hands, see if there difference, so.
(int = 0; i< newlypaidorders.count; i++) { var paidorder = newlypaidorders.elementat(i); foreach ( var paiditem in paidorder.orderitems ) { shoporderitemstatus sois = new shoporderitemstatus { status = "paid", agent = "cronjob", shoporderitem = paiditem, comment = "" }; shopdb.shoporderitemstatus.add(sois); } paidorder.status = "paid"; }
and there is.. works intended, createdate/modifieddates not null. why original not work? can't head around concept (a) new entity added database.. automatic detectchanges() system must working... , surely had "added()" state... (b) somehow state not sufficient found in filter newly added items , created/modifieddate fields weren't updated.
Comments
Post a Comment