title: LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
body: <p>I have the following generic extension method:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static T GetById&lt;T&gt;(this IQueryable&lt;T&gt; collection, Guid id) 
      where T : IEntity
  {
      Expression&lt;Func&lt;T, bool&gt;&gt; predicate = e =&gt; e.Id == id;
  
      T entity;
  
      // Allow reporting more descriptive error messages.
      try
      {
          entity = collection.SingleOrDefault(predicate);
      }
      catch (Exception ex)
      {
          throw new InvalidOperationException(string.Format(
              "There was an error retrieving an {0} with id {1}. {2}",
              typeof(T).Name, id, ex.Message), ex);
      }
  
      if (entity == null)
      {
          throw new KeyNotFoundException(string.Format(
              "{0} with id {1} was not found.",
              typeof(T).Name, id));
      }
  
      return entity;
  }
  </code></pre>
  
  <p>Unfortunately Entity Framework doesn't know how to handle the <code>predicate</code> since C# converted the predicate to the following:</p>
  
  <pre class="lang-cs prettyprint-override"><code>e =&gt; ((IEntity)e).Id == id
  </code></pre>
  
  <p>Entity Framework throws the following exception:</p>
  
  <blockquote>
    <p>Unable to cast the type 'IEntity' to type 'SomeEntity'. LINQ to
    Entities only supports casting EDM primitive or enumeration types.</p>
  </blockquote>
  
  <p>How can we make Entity Framework work with our <code>IEntity</code> interface?</p>