title: Linq, lambda expression and OrderBy
body: <p>I have this generic method in my repository:</p>
  
  <pre><code>public T GetFirstOrDefault(Expression&lt;Func&lt;T, bool&gt;&gt; where, Expression&lt;Func&lt;T, object&gt;&gt; keySelector, bool ascending)
  {
      if (ascending)
      {
          return dbset.Where(where).OrderBy(keySelector).FirstOrDefault&lt;T&gt;();
      }
      else
      {
          return dbset.Where(where).OrderByDescending(keySelector).FirstOrDefault&lt;T&gt;();
      }
  }
  </code></pre>
  
  <p>And I would like to be able to use it like this, where DateCreated is of type DateTime:</p>
  
  <pre><code>someRepository.GetFirstOrDefault(m =&gt; m.myprop == someValue, m =&gt; m.DateCreated, true);
  </code></pre>
  
  <p>and like this, where Id is of type Int:</p>
  
  <pre><code>someRepository.GetFirstOrDefault(m =&gt; m.myprop == someValue, m =&gt; m.Id, true);
  </code></pre>
  
  <p>and like this, where Name is of type string:</p>
  
  <pre><code>someRepository.GetFirstOrDefault(m =&gt; m.myprop == someValue, m =&gt; m.Name, true)
  </code></pre>
  
  <p>However, it gives me the following error when I use it:</p>
  
  <p><strong>Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.</strong></p>
  
  <p>After doing some research, I found out that maybe I have to use a keySelector of type <code>Expression&lt;Func&lt;TSource, TKey&gt;&gt;</code> or something like that, and this is where I am getting confused. If I declare my method like this, I am not sure where TKey should be coming from:</p>
  
  <pre><code>public T GetFirstOrDefault(Expression&lt;Func&lt;T, bool&gt;&gt; where, Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector, bool ascending) { }
  </code></pre>
  
  <p>Am I on the right path? How should my OrderBy clause be declared?</p>