title: Entity Framework: select property as Object
body: <p>I'm running into some trouble when trying to retrieve property values as Objects instead of their respective types. The following code throws this exception:</p>
  
  <pre><code>Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
  </code></pre>
  
  <p>This code works fine when selecting a string, but not when selecting DateTimes, Integers or Nullable types.</p>
  
  <pre><code>public class Customer
  {
      public int Id { get; set; }
  
      public string Name { get; set; }
  
      public DateTime CreatedOn { get; set; }
  }
  
  public class Program
  {
      public static void Main(string[] args)
      {
          using (var ctx = new MyContext())
          {
              // Property selector: select DateTime as Object
              Expression&lt;Func&lt;Customer, object&gt;&gt; selector = cust =&gt; cust.CreatedOn;
  
              // Get set to query
              IQueryable&lt;Customer&gt; customers = ctx.Set&lt;Customer&gt;();
  
              // Apply selector to set. This throws: 
              // 'Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.'
              IList&lt;object&gt; customerNames = customers.Select(selector).Distinct().ToList();
  
          }
      }
  }
  
  public class MyContext : DbContext
  {
  
  }
  </code></pre>
  
  <p>The end goal is a generic filtering to select distinct values from any of an object's properties.</p>