Using Audit.EntityFramework, how can I set the values of a foreign key to a property on the related entity? #653
motoyugota
started this conversation in
General
Replies: 2 comments 1 reply
-
This is because, in some cases, we don't know the IDs until the entity is persisted, such as in the case of database-generated IDs. That's why the library tries to update the audit event IDs after saving the entities. Maybe, a new setting could be included to indicate you want to ignore those updates to the PK and FKs. I will think about it a little bit more... |
Beta Was this translation helpful? Give feedback.
0 replies
-
Another option could be to use a custom OnSaving action (which occurs right before saving the audit event) to update the properties. For example: Audit.Core.Configuration.AddOnSavingAction(scope =>
{
foreach (var entry in scope.GetEntityFrameworkEvent().Entries)
{
if (entry.EntityType == typeof(Product))
{
entry.ColumnValues["ProductType"] = relatedObject.Name;
foreach (var change in entry.Changes)
{
if (change.ColumnName == nameof(Product.ProductType))
{
change.OriginalValue = relatedObject.Name;
change.NewValue = ...;
}
}
}
}
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to set the name of the related entity in the OriginalValue and NewValue properties of the EventEntryChange object (and possibly in the ColumnValues object as well). I have tried to use the Format and Override options like this (just simplified code to show it):
In both cases, it will replace the OriginalValue with the updated value, but the NewValue and ColumnValues entry get reset to the foreign key ID. This is because of this code in DbContextHelper:
In all honesty, I'm not really sure why it is doing this with the audit entry, but I'm sure there's a reason. However, I'm still stuck trying to figure out how I can get that logging to work, or even something similar that would fit my needs.
Beta Was this translation helpful? Give feedback.
All reactions