zzzprojects / EntityFramework-Plus

Entity Framework Plus extends your DbContext with must-haves features: Include Filter, Auditing, Caching, Query Future, Batch Delete, Batch Update, and more
https://entityframework-plus.net/
MIT License
2.27k stars 318 forks source link

Humanize Audit Entry #106

Open maharatha opened 7 years ago

maharatha commented 7 years ago

Hi -

I am working on the Audit Entry where I would like to humanize the modifications based on change in certain property.

E.g. If the amount is increased or decreased I would to add a new column in the Audit Entry Property table "Activity" and insert saying Amount Reduced.

Similarly if the property let's say IsPost changed from 0 to 1 I would like to record that Activity as Posted.

Do you think you can help me on achieving something like this ?

zzzprojects commented 7 years ago

Hello @maharatha ,

There is some place you could place similar code. I believe the best place is probably when the library has created all auditEntries and auditEntryProperties.

Here is an example that add a new AuditEntryProperty when the ColumnInt value is greater than five.

audit.Configuration.AutoSavePreAction = (context, audit2) =>
{
    foreach (var entry in audit.Entries)
    {
        if (entry.Entry != null && entry.Entry.Entity is EntitySimple)
        {
            var entity = (EntitySimple) entry.Entry.Entity;

            if (entity.ColumnInt > 5)
            {
                entry.Properties.Add(new AuditEntryProperty() { PropertyName = "GreaterThan", NewValue = "5"});
            }
        }
    }
    (context as CurrentContext).AuditEntries.AddRange(audit.Entries);
};

This is probably a good example too let you getting started. Let me know if you need more help or this example was enough to find your solution.

Best Regards,

Jonathan

maharatha commented 7 years ago

Thank you for responding so quick. But my requirement is to access the old and new value and then decide on what to insert.

The example you gave would suffice half of my requirement but it would accommodate most of it if I have access to the old and new value before inserting.

zzzprojects commented 7 years ago

You can easily access to old value by finding it either in the properties list or using the ObjectStateEntry

var oldValue = entry.Entry.OriginalValues["ColumnInt"];
var newValue1 = entity.ColumnInt;
var newValue2 = entry.Entry.CurrentValues["ColumnInt"];