I am trying to get primary key information for each entry that I am inserting, updating, or deleting in an EF5 application. I use code similar to 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 is not working when a new record is being inserted into the database. When the entry's state is EntityState.Added, the key.EntityKeyValues has a null value (this code set the value of keyName to "(NotFound)".
Is there a way to get the column name for the primary key when a record is being inserted?
I figured out a way to do it, combining my original code with code from the link Gert posted:
//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)
{
    EntitySetBase setBase = ObjectContext.ObjectStateManager
        .GetObjectStateEntry(entry.Entity).EntitySet;
    string[] keyNames = setBase.ElementType.KeyMembers.Select(k => k.Name).ToArray();
    string keyName;
    if (keyNames != null)
        keyName = keyNames.FirstOrDefault();
    else
        keyName = "(NotFound)";
}
So far, it seems to be working, even when I add a new record.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With