Example of overriding OnScopeSaving #529
-
Hi, I'm in the process of integrating Audit.EntityFramework in my project; I'm storing the audit output in the same DB as the real entities, using the EntityFramework data provider, and I need to ensure that both the real entity and the audit entity are saved within the same transaction. I understand that I need to override OnScopeSaving and use NullDataProvider instead of EntityFramework data provider, but I have no idea how to do the "custom log saving" mentioned in the documentation. @thepirat000, can you - or anyone else - please provide a working example? Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi. It really depends on your configuration and EF version. I'm assuming that you:
Then my recommendation is to:
So, on your startup, this is how you can configure the custom actions to begin / commit the transaction: Audit.Core.Configuration.Setup().UseEntityFramework(/*your custom configuration*/);
// Begin a transaction for each saving operation
Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, async scope =>
{
await scope.GetEntityFrameworkEvent().GetDbContext().Database.BeginTransactionAsync();
});
// Commit the transaction for each saving operation
Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaved, async scope =>
{
await scope.GetEntityFrameworkEvent().GetDbContext().Database.CommitTransactionAsync();
}); In this way, both saving operations will be performed within the same transaction. Note you cannot use the overrides on your |
Beta Was this translation helpful? Give feedback.
-
Note that an OnScopeSaved() virtual method was added to the AuditDbContext |
Beta Was this translation helpful? Give feedback.
Note that an OnScopeSaved() virtual method was added to the AuditDbContext