0

I try to use ChangeTracker from EF to do audit and save all changes in database (add + update).

So with ChangeTracker I will able to get all changed tables, and all values for each. But I also need of the ID of new records in new tables.

Some of them are relationship, and when I try to get the values with EntityKey, the primary key is 0

private object GetPrimaryKeyValue(DbEntityEntry entry)
{
    var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
    return objectStateEntry.EntityKey.EntityKeyValues[0].Value;    
}

Someone knows, if I'm on the wrong way and if it's possible to get the primary key of related entity ?

Thanks !

  • I think you need to check your database table. If it is a primary key, it cannot be null (see http://stackoverflow.com/questions/3876785/sql-server-cant-insert-null-into-primary-key-field). – user8128167 Dec 15 '15 at 17:13
  • In fact, I said something wrong, it's not null but 0. The primary key is an autoincremented field in the table. – Dervis Findik Dec 15 '15 at 18:06

1 Answers1

0

I think you get 0 (that is default(int)) because autoincremented (identity) columns get populated only after save is done (i.e. dbContext.SaveChanges has finalized successfully). Try reading the value after SaveChanges() like suggested here.

It looks like a way to catch newly added values, you must override SaveChanges and get generated values yourself like mentioned here.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • Yes, but what I want to do is to save into another table all new added values, for that I retrieves all them with ChangeTracker of EF. When it concerns a update of existing data, it's not a problem, but in this case it's for new rows and the primary key is 0 – Dervis Findik Dec 15 '15 at 19:09
  • I have put an extra reference in my answer. – Alexei - check Codidact Dec 15 '15 at 19:23
  • Just a small note: As I do not like triggers, I favor .NET solutions. However, keep in mind that triggers might be more suitable if table data can be changed by other application than your own. – Alexei - check Codidact Dec 15 '15 at 19:25
  • Ok Alexei, your advice and references don't help me because I had the same result, **0** for the primary key. If I do my audit after calling `SaveChanges()`, I lose the `EntityState` value (added in this case) but if check the state `Unchanged` my new added object is there with all values and so with the **ID**. Do you think is right to use the state unchanged after calling `SaveChanges()` for new added object ? – Dervis Findik Dec 16 '15 at 08:04