Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Primary Key of DBEntityEntry when Adding

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?

like image 216
Pizzor2000 Avatar asked Sep 09 '14 16:09

Pizzor2000


1 Answers

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.

like image 72
Pizzor2000 Avatar answered Oct 15 '22 13:10

Pizzor2000