title: Linq error: The cast to value type 'Int32' failed because the materialized value is null
body: <p>... But it's not null.</p>
  
  <p>FYI - Many threads exist on this error, but none that I've seen using an anonymous type.</p>
  
  <p>I'm Getting an odd InvalidOperationException in a Linq query.</p>
  
  <p>message: "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."</p>
  
  <p>The confusing thing is that it's erroring when creating an anonymous type:</p>
  
  <pre><code>var workstepid = 484,449;
  
  var wsData = ion.xWorkSteps
     .Where(w =&gt; w.WorkStepId == workstepId)
     .Select(w =&gt; new
     {
         w.WorkStepId,
         w.ServiceId,
         w.Service.TitleId,
         w.Service.Title.OrderId,
         w.Service.Title.AltTitleId
     }).SingleOrDefault();
  </code></pre>
  
  <p>In LinqPad this particular query runs just fine and the workstepId used returns an integer value for each property of the anonymous type.  So why a casting error when there is no null value for any property!?</p>
  
  <p>FYI, the last property AltTitleId is a nullable int, and the other properties are ints.
  Also, this code was written weeks ago and I didn't get this error until today.  Is something funky w/ my EF?</p>
  
  <p><strong>Edit:  SOLVED</strong></p>
  
  <p>We use soft-delete in our db's, setting deleted records to Acive=0.
  It turns out that there is a property set in EF  on the edmx tables filtering out inactive records (filter for Active=1).  Naturally, this wouldn't effect Linqpad which gives me the expected result, but since this was an older record I was testing, the title record (Service.Title) had been marked Active=0 and was therefore returning null.</p>
  
  <p>Thanks to everyone for the help.</p>