title: How to get primary key value with Entity Framework Core
body: <p>We are currently using the method below which depends upon IObjectContextAdapter in an abstract Repository.  From what I'm reading, it appears that anything related to ObjectContext is being chopped out of Entity Framework Core.  The method below is the only place we depend upon anything related to ObjectContext. </p>
  
  <p>We'd like to upgrade to Entity Framework Core.  This is our only road block.  Is there a way to get the value of the primary key of an entity with the Entity Framework Core apis?</p>
  
  <pre><code>// Entity Framework
  public virtual int GetKey(T entity)
  {
      var oContext = ((IObjectContextAdapter)_DbContext).ObjectContext;
      var oSet = oContext.CreateObjectSet&lt;T&gt;();
      var keyName = oSet.EntitySet.ElementType
                                  .KeyMembers
                                  .Select(k =&gt; k.Name)
                                  .Single();
  
      return (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
  }
  </code></pre>