title: Entity Framework: ObjectSet and its (generics) variance
body: <p>I use: EntityFramework + POCO</p>
  
  <p>Here is the thing:</p>
  
  <pre><code>public interface IBaseType
  {
      int Id { get; set; }
  }
  
  public class BaseType : IBaseType
  {
      public virtual int Id { get; set; }
  }
  
  public class DerivedType : BaseType
  {
  }
  </code></pre>
  
  <p>The problem:</p>
  
  <pre><code>public class EntityFetcher&lt;T&gt; where T : BaseType
  {
      public object GetById(int id)
      {
          ObjectSet&lt;T&gt; objectSet = (ObjectSet&lt;T&gt;)GetTheObjectSet(typeof(T)); 
  
          return objectSet.SingleOrDefault((o) =&gt; o.Id == id);
      }
  }
  </code></pre>
  
  <p>If <code>T</code> is <code>BaseType</code> this all works perfectly, but:
  The problem is that in EntityFramework when one class inherits another they share the <code>ObjectSet</code> and, therefore, if <code>T</code> is <code>DerivedType</code> then the <code>GetTheObjectSet</code> returns <code>ObjectSet&lt;BaseType&gt;</code>, which cannot be cast to <code>ObjectSet&lt;DerivedType&gt;</code>. </p>
  
  <p>Is there a way to actually cast this this thing or somehow else execute the <code>SingleOrDefault</code>? Can those things be cast using the <code>IObjectSet&lt;&gt;</code> and <code>IBaseType</code>?</p>