title: Generic Repository GetByID method with "Including" ....
body: <p>I am trying to add a method to my generic repository that will allow me to query an entity by it's PrimaryKey (ID) and select what navigation properties to return. The kicker is, that in order to be truly generic I do not know the data type or field name of the Primary Key (Not supporting compound keys ... yet).</p>
  
  <p>So here's what I started with ... the below snippet gets me the TEntity based on  key regardless of the TYPE of the key ...  </p>
  
  <pre><code> public virtual TEntity GetByID(Object entityID)
   {
       TEntity ret = DbSet.Find(entityID);
       return ret;
   }
  </code></pre>
  
  <p>The next step was to get records back, but including whatever navigation fields I chose to include ... This worked out great for that ... for multiple records.</p>
  
  <pre><code>    public virtual IQueryable&lt;TEntity&gt; GetAllIncluding(params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includedProperties)
      {
          var query = DbSet.AsQueryable();
  
          foreach (var prop in includedProperties)
          {
              query = query.Include(prop);
          }
  
          return query;
      }
  
     //
     // example usage gets ALL books including Author and Publisher information
     var repo = uow.GetRepository&lt;Book&gt;();
     repo.GetAllIncluding(e=&gt;e.Author, e=&gt;e.Publisher);
  </code></pre>
  
  <p>So now I need to mix the two ... here's the rub. In order to dynamically add the "including" expressions I need to convert the DbSet to an IQueryable ... however in order to leverage the type-agnostic key lookup I need to use the "Find()" method on the DbSet ... </p>
  
  <p>So in theory I need to convert the DbSet to an IQueryable, add the Include expressions then convert the IQueryable BACK to a DbSet so that I can access the type-agnostic "Find()" method ... this does not work ...</p>
  
  <p>Anyone got any ideas on how this can be done ... ??</p>
  
  <hr>
  
  <p>Here's some pseudo-code for what I am trying to get to work ... </p>
  
  <pre><code>    public virtual TEntity GetByID(Object entityID, params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includedProperties)
      {
          var query = DbSet.AsQueryable();
  
          foreach (var prop in includedProperties)
          {
              query = query.Include(prop);
          }
  
  
          TEntity ret = ((DbSet)query).Find(entityID);
          return ret;
      }
  </code></pre>