1

I have a EF 6 DB first MVC 5 application. My requirement is to do audit logging of every operation (including read). I went through many posts and have few queries:

  1. Should audit logging be done at EF level (by overriding SaveChanges) or DB level (by using triggers). Which is the recommended way.
  2. I want to log one row per entity change instead of per property change. What am I thinking is to make a valid XML schema but then each entity will have different schema depending on the column. Any other inputs on how to achieve this
  3. I want log for read operation too
  4. Last thing is, client wants to maintain checksum value per row using SHA3 or MD5.

Considering above points, what is the suggested approach. I could really use some pointers.

Garima
  • 401
  • 5
  • 29
  • 1
    If you want to audit even read then you need to implement a wrapper for your DBContext and then audit the operation of `wrapper` , `SaveChanges()` can audit `Added` and `Modified` entity not read entity like https://stackoverflow.com/questions/43466550/hold-old-and-new-value-in-savechange-as-dbentityentry-entity-to-audit, if your audit is complicated then use the proper `Audit` utility. – Aria Jan 23 '19 at 08:47
  • Thanks for your comment, any recommended `Audit` utility? I see that you used `Audit.Net` – Garima Jan 23 '19 at 08:58
  • 2
    You are Welcome, yes I am using `Audit.Net` it is power and reliable, before this I implemented my custom audit which was not proper and reliable, it will give you `Old` and `New` value as you expected, but for auditing `Select` you should implement it such as a wrapper. – Aria Jan 23 '19 at 09:01
  • Yes `Read` is really problematic and i am not sure how detailed will you go in it. Using Navigation properties you can read multiple entries while reading only one. That's why I asked point 1 whether I should go with DB triggers. – Garima Jan 23 '19 at 09:06
  • 1
    No, I think it is not worth used DB trigger to know if row read or not, Suppose you have an entity named `Entity` then it is enough to implement a class for sample named `EntityManagement` which have a method named `Get(id)` which returns specific `Entity` then in `Get(id)` you can do `Read Audit`, I think the `DBContext` should not be accessible out, `DbContext` should used in some wrapper, then if a developer need to manipulate data the should use those wrapper not `DbContext` directly. – Aria Jan 23 '19 at 09:14

1 Answers1

0

To achieve this, I did not use any utility as my requirements were bit different. Finally I went ahead with overriding the SaveChanges method of DbContext used by EF. Also used Newtonsoft JSON library to convert whole updated object to JSON and save it.

To get complete code, check this link - How to audit MVC app which used EF DB first approach

Garima
  • 401
  • 5
  • 29