title: EF Auditing Creations
body: <p>Ok there's a lot going on here and I don't want to bore you guys with a very long winded code sample so here's an extract ...</p>
  
  <p>When SaveChangesAsync() is called on my EF context I have it calling this method to audit each entry ...</p>
  
  <pre><code>async Task Audit(DbEntityEntry&lt;IAmAuditable&gt; entry)
  {
      try
      {
          var newAuditEntry = new AuditEntry
          {
              EntityType = entry.Entity.GetType().Name,
              Event = entry.State.ToString(),
              SSOUserId = kernel.Get&lt;User&gt;().Id,
              EntityId = entry.GetId().ToString(),
              EventId = eventId
          };
  </code></pre>
  
  <p>In the event that the entry in question is an entity creation which will result in an insert on the db i then also do this ...</p>
  
  <pre><code>var properties = entry.CurrentValues.PropertyNames.Select(p =&gt; entry.Property(p)).ToList();
  var addedValues = new List&lt;AuditDataItem&gt;();
  
  foreach (var p in properties)
  {
      addedValues.Add(new AuditDataItem
      {
          PropertyName = p.Name,
          PreviousValue = null,
          NewValue = p.CurrentValue.ToString()
      });
  }
  newAuditEntry.Changes = addedValues;
  break;
  </code></pre>
  
  <p>... this is where it falls over ... at that point in time the base call to SaveChanges hasn't yet been executed so the entity in question does not yet have a primary key value ... the net result is that I log the creation of an entity with no primary.</p>
  
  <p>Does anyone have suggestions on a nice clean way to handle this so I can put the new primary key value in to an AuditDataItem?</p>
  
  <p>EDIT: </p>
  
  <p>Here's an example of what I am logging at the moment as json, this is a single AuditEntry object and a partial of some of the child AuditDataItem rows ...</p>
  
  <pre><code>   {
        "Id": 4,
        "SSOUserId": 1,
        "EventId": "6d862aad-0898-4794-aea0-00af6f2994ff",
        "EntityType": "AC_Programme",
        "Event": "Added",
        "TimeOfEvent": "2016-02-04T12:04:31.5501508+01:00",
        "Changes": [
          {
            "Id": 34,
            "PropertyName": "Id",
            "PreviousValue": null,
            "NewValue": "0"
          },
          {
            "Id": 35,
            "PropertyName": "Name",
            "PreviousValue": null,
            "NewValue": "Test"
          },
          ...
        ]
      }
  </code></pre>