1

Our application uses nHibernate, and there is a requirement to log all changes to a certain table. I don't need to log the entire queries generated by the ORM, just the data and the date.

For example, let's say I have an entity called Employee:

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

The only solution I can think of is manually keeping track of changes (new, updated and deleted entities) and logging that data to a table. Something along the lines of:

public void SaveEmployees(List<Employee> employees)
{
    employees.ForEach(x => {
        if (x.ID == 0) // add do LOG list as new
        else // add to LOG list as old
    });

    // save employees like usual
    // save LOG list
}

This isn't difficult to do, even with fetching the old data to see what's missing, but I was wondering if there was a better way?

dzenesiz
  • 1,388
  • 4
  • 27
  • 58
  • As you said you do not want to log the queries. Just in case you choose that option, [here](https://stackoverflow.com/a/54480679/5779732) is the way explained. – Amit Joshi May 08 '19 at 06:47
  • Transaction logs have nothing to do with NHibernate. You are asking about *auditing* and typically, it's something you do in the *database*, not a client-side ORM tool. All major databases have auditing or change tracking mechanisms that can be used to audit data changes – Panagiotis Kanavos May 08 '19 at 11:04
  • Which database are you targeting? For example, in SQL Server you can use the built-in auditing feature, you can use change tracking to periodically pick and store changes or, in SQL Server 2017 and later, you can use temporal tables to track changes in a history table – Panagiotis Kanavos May 08 '19 at 11:06

1 Answers1

0

I think an Interceptor might give you what you need. You can use the OnFlushDirty() or the OnSave() method to write your changes. Documentation here.

David Osborne
  • 6,436
  • 1
  • 21
  • 35