Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Entity Before Deleting

How can I update audit information contained in an entity before actually deleting it? I'm working on a class derived from DbContext.

I tried by changing the state to Modified, then set the updated info, then calling base.SaveChanges(), then marking it as Deleted. The problem comes when I try to call SaveChanges after setting the updated info. It appears that the other objects of the relation are marked as Deleted and I get this exception:

"A relationship from the 'ChildrenEntity' AssociationSet is in the 'Deleted' state. Given    multiplicity constraints, a corresponding 'ParentEntity' must also in the 'Deleted' state." 

Thanks!

like image 654
Luis Aguilar Avatar asked Dec 11 '25 22:12

Luis Aguilar


1 Answers

Yes this is problematic and you will probably not find better way then using before delete trigger in the database. If you want to handle it in the application the working way will be:

  • Iterate all records in context.ObjectStateManager.GetObjectStateEntires and storing actual state for each entry into some temporary data structure.
  • Set all entries to unchanged state except those you want to modify first.
  • Call SaveChanges for the first time
  • Iterate all state entries again and set them state stored in temporary data structure
  • Call SaveChanges again

You should do the whole operation in TransactionScope

like image 181
Ladislav Mrnka Avatar answered Dec 14 '25 12:12

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!