3

Assuming I have an application that allows customers to add/update products into my database over Web API. I have lightweight DTOs like this:

public class ProductDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

What is the industry practice to track entities, assuming I would want to store the changes into an Audit table. E.g., display old price vs new price

Upon receiving the DTO in my WebAPI controller, do I have to query from the database the current record, do an object comparison, and save the differences? - Is this the only way?

Null Reference
  • 11,260
  • 40
  • 107
  • 184
  • The audit table would be the way to go; however, you may also want to know "who changed this record" and various other data which the audit table may not support. In which case, you should consider persisting to a separate entity. – user1477388 May 06 '14 at 14:00
  • Would the only way to compare the object I receive via WebAPI be to first retrieve the existing record from my database to compare? – Null Reference May 06 '14 at 14:09
  • Basically, what I am saying is create a separate entity called Product_Audit which functions the same as an audit table except you must populate the contents in your application (SQL won't do it for you). That way, you can add all the additional info you want such as a user ID for tracking who updated the record. For comparisons, you would simply join this table `on ProductDTO.Id equals Product_Audit.ProductId`. – user1477388 May 06 '14 at 14:15

1 Answers1

1

Web API has built-in logging and tracing and here is a good walkthrough.

Here is a TraceWriter implementation using log4net or if NLog is more your cup of tea then there is an NLog trace logger, and here is another example using NLog.

If you want to compare changes, then you'd need to set something up manually. You can easily get access to the JSON requests. It would simply be a matter or running a diff between the old and the new objects. An example of which is on StackOverflow. I would log the request headers, request body, endpoint address, an API key, the old object (request) and the diffs. You could then either output the comparisons as a list of differences, or have a side-by-side comparison (as you see in Git / SVN / TFS merge).

Community
  • 1
  • 1
Rebecca
  • 13,914
  • 10
  • 95
  • 136
  • I'm not looking so much for logging, as I am in trying to track the DTO and to see which are the properties that are changed, so I can save the differences into an Audit table – Null Reference May 06 '14 at 14:36
  • See the last part of my answer then. You would need to do this manually in code. Get the new DTO, load the old DTO. Compare the two and output the differences as a list of changes. I.e. Field 'X' changed from 'A' to 'B'. The example I pointed you to does this quite nicely. – Rebecca May 06 '14 at 14:59