I’m using the following code to create an audit trail in an MVC3 app.
In the code sample they are using GUIDs for primary keys. In my case I’m using Identity columns that auto-increment. The code in the link above works great, except on ‘add’ I can’t get the primary key (return 0 as the for does not submit this data) when calling dbentry.current values.
I’m trying to find a way to get the primary key so I can properly add it to my transactions table. I know you can retrieve this afterwards, but I’m not sure the best way to get that and then update the table with the correct primary key.
Any ideas would be appreciated. I’d prefer not to change my primary keys to GUIDs.
I made the following modifications to my dbcontext which works.
if (ent.State == System.Data.EntityState.Added)
{
base.SaveChanges();
ent.State = System.Data.EntityState.Added;
}
then in the GetAuditRecordsForChange function I detached again so the record isn’t created twice.
if (dbEntry.State == System.Data.EntityState.Added)
{
// For Inserts, just add the whole record
// If the entity implements IDescribableEntity, use the description from Describe(), otherwise use ToString()
result.Add(new TransactionHistory()
{
TransactionTypeID = 1,
TableName = tableName,
FieldName = "ALL",
RecordPK = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(),
OldValue = null,
NewValue = (dbEntry.CurrentValues.ToObject() is IDescribableEntity) ? (dbEntry.CurrentValues.ToObject() as IDescribableEntity).Describe() : dbEntry.CurrentValues.ToObject().ToString(),
TransactionBy = userId,
TransactionDate = changeTime,
TransactionApplication = "Galactus"
});
dbEntry.State = System.Data.EntityState.Detached;
}
You cannot do it in single run with database generated PK. That is the reason why the post uses GUIDs. The PK of record to be inserted is known only after the insertion = after you execute
SaveChanges. So you need to build your insertion log after that andSaveChangesagain.