I am trying to get primary key information for every record that I insert, update or delete in an EF5 application. I am using code like this:
//Get collection of each insert, update, or delete made on the entity. IEnumerable<DbEntityEntry> changedEntries = this.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted); foreach (DbEntityEntry entry in changedEntries) { //Get primary key collection EntityKey key = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager .GetObjectStateEntry(entry.Entity).EntityKey; string keyName; //Get name of first key. Make sure a collection was returned. if (key.EntityKeyValues != null) keyName = key.EntityKeyValues[0].Key; else keyName = "(NotFound)"; }
The problem with this code, however, is that it does not work when a new record is inserted into the database. When the state of the entry is EntityState.Added, the key .EntityKeyValues has a value of zero (this code sets the value of keyName to "(NotFound)".
Is there a way to get the column name for the primary key when inserting a record?
source share