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 chan开发者_C百科ging 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!
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
精彩评论