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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…