Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the primary key value of an arbitrary entity in code first

Is there such a method?

object GetPrimaryKeyValue(DbEntityEntry entry);

Or how should it be implemented?

like image 233
Kornél Regius Avatar asked Aug 31 '11 09:08

Kornél Regius


Video Answer


1 Answers

You need to cast your DbContext to IObjectContextAdapter so you can access the underlying ObjectContext which gives you access to some more advanced features hidden by DbContext.

Inside your class which derives DbContext the following method will work.

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

If there is more than one key then you should iterate over the EntityKeyValues property.

like image 121
dan Avatar answered Oct 02 '22 19:10

dan