title: How can I compare a nullable type date using user entered date?
body: <p>I can't find how to compare a date entered by a user to a date on a table created by EF6. I'm using LINQ Extensions to search the DB and have tried multiple suggestions that compile, but fail during execution.</p>
  
  <p><strong>User Input:</strong></p>
  
  <pre><code>DateTime userdate;
  DateTime.TryParse(search.Value, out userdate);
  </code></pre>
  
  <p><strong>Attempts so far:</strong></p>
  
  <pre><code>a = dbContext.Messages.Where(x =&gt; x.Date.Date == userdate.Date); // doesn't compile
  a = dbContext.Messages.Where(x =&gt; x.Date.Value.Date == userdate.Date); // error # 4
  a = dbContext.Messages.Where(x =&gt; x.Date.ToString() == userdate.Date.ToString()); // issue #2
  a = dbContext.Messages.Where(x =&gt; x.Date.Value.ToString() == userdate.Date.ToString()); // issue #2
  a = dbContext.Messages.Where(x =&gt; Object.Equals(x.Date, userdate.Date)); // throws error #1
  a = dbContext.Messages.Where(x =&gt; Object.Equals(x.Date.Date, userdate.Date)); // throws error #1
  </code></pre>
  
  <p>I've tried searching this a million times and find solutions that compile, yet always throw an error when executed. </p>
  
  <p>There was a version of the <code>ToString()</code> that worked, but it generated a long date string such as <code>May 12, 2005 00:00:00</code> and trying to turn my userdate into a long date to compare just seems like it would create too much overhead when searching through millions of records.</p>
  
  <p>I'm fresh out of ideas here. </p>
  
  <p>Issues:</p>
  
  <ol>
  <li><blockquote>
    <p>Unable to cast the type 'System.Nullable``1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.</p>
  </blockquote></li>
  <li><p>Doesn't find any matches, even with exact datetime</p></li>
  <li><p>Magically works all of a sudden.</p></li>
  <li><blockquote>
    <p>The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.</p>
  </blockquote></li>
  </ol>
  
  <p><strong>Final solution</strong>
  Based on the selected answer, I found that the SqlFunctions class has a .DateDiff method which maps to the T-SQL DateDiff function. I used that to count the number of days between the two dates and selected only the ones that returned 0. That allowed me to compare the dates without having to do any conversion on the SQL side.</p>