title: Entity Framework 4: How to find the primary key?
body: <p>I am trying to create a generic method using EF4 to find the primary key of an object. </p>
  
  <p>example</p>
  
  <pre><code>public string GetPrimaryKey&lt;T&gt;()
  {
      ...
  }
  </code></pre>
  
  <p>To give more info I am working off of the Tekpub StarterKit and below is the class I am trying to get up and running</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Data.Objects;
  using System.Data.Objects.ELinq;
  using System.Data.Linq;
  using Web.Infrastructure.Storage.EF4;
  
  namespace Web.Infrastructure.Storage {
  public class EFSession:ISession {
      PuzzleEntities _db;//This is an ObjectContext
      public EFSession() {
          _db = new PuzzleEntities();
      }
  
      public void CommitChanges() {
          _db.SaveChanges();
      }
      /// &lt;summary&gt;
      /// Gets the table provided by the type T and returns for querying
      /// &lt;/summary&gt;
      private ObjectSet&lt;T&gt; GetObjectSet&lt;T&gt;() where T:class {
          return _db.CreateObjectSet&lt;T&gt;();
      }
  
      private T GetByPrimaryKey&lt;T&gt;() where T: class
      {
          .....
      }
  
      public void Delete&lt;T&gt;(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; expression) where T: class{
  
          foreach (T item in All&lt;T&gt;().Where(expression))
          {
              GetObjectSet&lt;T&gt;().DeleteObject(item);
          }
      }
  
      public void Delete&lt;T&gt;(T item) where T : class {
          GetObjectSet&lt;T&gt;().DeleteObject(item);
      }
  
      public void DeleteAll&lt;T&gt;() where T : class {
          foreach(T item in All&lt;T&gt;())
          {
              GetObjectSet&lt;T&gt;().DeleteObject(item);
          }
      }
  
      public void Dispose() {
          _db.Dispose();
      }
  
      public T Single&lt;T&gt;(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; expression) where T:class {
          return GetObjectSet&lt;T&gt;().SingleOrDefault(expression);
      }
  
      public IQueryable&lt;T&gt; All&lt;T&gt;() where T : class {
          return GetObjectSet&lt;T&gt;().AsQueryable();
      }
  
      public void Add&lt;T&gt;(T item) where T : class {
          GetObjectSet&lt;T&gt;().AddObject(item);
      }
      public void Add&lt;T&gt;(IEnumerable&lt;T&gt; items) where T : class {
          foreach (T item in items)
          {
              GetObjectSet&lt;T&gt;().AddObject(item);
          }
      }
      public void Update&lt;T&gt;(T item) where T : class {
          //nothing needed here
      }
  }
  }
  </code></pre>