title: How to get list of database table primary key columns in EF Core
body: <p>ASP.NET Core MVC application using EF Core. In Linq to SQL, this code returns list of database table primary key columns names:</p>
  <pre><code>    /// &lt;summary&gt;
      /// Database primary key names
      /// &lt;/summary&gt;
      public IList&lt;string&gt; DatabasePrimaryKey(Type dbContextPocoType)
      {
          List&lt;string&gt; pk = new List&lt;string&gt;();
  
          foreach (PropertyInfo p in dbContextPocoType.GetProperties())
          {
              var ca = p.GetCustomAttributes(typeof(ColumnAttribute), true);
  
              if (ca.Length == 0) continue;
              var atr = (ColumnAttribute)ca.Single();
  
              if (!atr.IsPrimaryKey) continue;
              pk.Add(atr.Name);
          }
  
          return pk;
      }
  </code></pre>
  <p>In EF Core I tried</p>
  <pre><code>var entry = ctx.Entry(dbContextPocoType);
  var primaryKey = entry.Metadata.FindPrimaryKey();
  
  IList&lt;string&gt;  keys = primaryKey.Properties.Select(x =&gt; x.Name).ToList();
  return keys;
  </code></pre>
  <p>But this returns C# property names - how to get database table column names in EF Core?</p>
  <p><strong>Update:</strong> using answer I created this method:</p>
  <pre><code>    public IList&lt;string&gt; DatabasePrimaryKey&lt;TPoco&gt;()
      {
          var entry = ctx.Entry(typeof(TPoco));
          var primaryKey = entry.Metadata.FindPrimaryKey();
          var entityType = ctx.Model.FindEntityType(typeof(TPoco).Name);
          var schema = entityType.GetSchema();
          var tableName = entityType.GetTableName();
          IList&lt;string&gt; keys = primaryKey.Properties
               .Select(x =&gt; x.GetColumnName(StoreObjectIdentifier.Table(tableName, schema)))
               .ToList();
          return keys;
      }
  </code></pre>
  <p>Can this method be improved?</p>