title: How can I get the Primary Key Field and Default Value of an Entity in Entity Framework 6?
body: <p>My database designer did not use the standard "Id" for Primary Key fields in my database, so I need to find the following things for my generic repository that I am writing.</p>
  
  <ul>
  <li>Primary Key Name </li>
  <li>Primary Key CLR Type </li>
  <li>Primary Key CLR Type Default value</li>
  </ul>
  
  <p>I am trying to take the Generated scaffolding code that looks like the following and make a generic repository:</p>
  
  <pre><code>    public void InsertOrUpdate(Entity entity)
      {
          if (entity.EntityID == default(int))
          {
              // New entity
              _context.Entry(entity).State = System.Data.Entity.EntityState.Added;
          }
          else
          {
              // Existing entity (TODO:  Wont add the whole graph of things)
              _context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
          }
      }
  </code></pre>
  
  <p>I have found the Primary Key Name by doing the following:</p>
  
  <pre><code>    public string FindPrimaryKey()
  {
      var objectSet = ((IObjectContextAdapter)_context).ObjectContext.CreateObjectSet&lt;Entity&gt;();
      string keyName = objectSet.EntitySet.ElementType.KeyMembers.Select(k =&gt; k.Name).FirstOrDefault();
      return keyName;
  }
  </code></pre>
  
  <p>I am close to getting the Primary Key CLR Type with the following code:</p>
  
  <pre><code>  public string FindPrimaryKeyType()
          {
              var objectSet = ((IObjectContextAdapter)_context).ObjectContext.CreateObjectSet&lt;Entity&gt;();
              string keyType = objectSet.EntitySet.ElementType.KeyMembers.Select(k =&gt; k.TypeUsage.EdmType.FullName).FirstOrDefault();
              var keyType2 = from m in objectSet.EntitySet.ElementType.KeyMembers
                  select m.TypeUsage.EdmType;
              return "";
          }
  </code></pre>
  
  <p>And I can see the ClrType when debugging the code above, but I haven't been able to figure out  how to get the Type from ClrType:</p>
  
  <p><img src="https://i.stack.imgur.com/3NSvr.png" alt="VS 2013 Debug screen shot"></p>
  
  <p>So, please help  me figure out how to get the ClrType, or another better idea on how to do this.  </p>