title: Possible reasons for error: "The cast to value type 'Decimal' failed because the materialized value is null"
body: <p>I'm getting a report of errors from a production system. I don't have easy access to the production system. I will get all the data that I need for it in due course, but what I'm trying to do is expedite the process of resolution of this issue. I'm trying to eliminate as much guesswork as possible.</p>
  
  <p>The error I'm getting this this:</p>
  
  <blockquote>
    <p>Extended Properties: Exception - System.InvalidOperationException: The
    cast to value type 'Decimal' failed
    because the materialized value is
    null. Either the result type's generic
    parameter or the query must use a
    nullable type.</p>
  </blockquote>
  
  <p>The code where the error is happening is this:</p>
  
  <pre><code>IQueryable&lt;AccountStatusModel&gt; result = from d in Context.Debtors
      where // Condition here
      select new AccountStatusModel
      {
           // All of the below are decimal in the AccountStatusModel
           // and all of them are decimal NOT NULL in the database
           NotYetDue = d.sometable.dbcurrent,
           DueThisMonth = d.sometable.dbprd1bal,
           Overdue = d.sometable.dbprd2bal
                  + d.sometable.dbprd3bal
                  + d.sometable.dbprd4bal
                  + d.sometable.dbprd5bal
                  + d.sometable.dbprd6bal,
           PaymentRecievedNotAllocated = d.sometable.dbunalloc,
           OutstandingOrders = d.dmoutordval ?? 0,
           TotalBalance = d.sometable.dbcurrent
                  + d.sometable.dbprd1bal
                  + d.sometable.dbprd2bal
                  + d.sometable.dbprd3bal
                  + d.sometable.dbprd4bal
                  + d.sometable.dbprd5bal
                  + d.sometable.dbprd6bal
                  + d.sometable.dbunalloc
                  + (d.dmoutordval ?? 0),
           CreditLimit = d.dmcredlim,
           LastPayment = d.dmvallastpaid,
  
           // Some other properties here
           // ....
      };
  </code></pre>
  
  <p>Before someone comments on the field names, assume that these are fake names. =)
  Note, that all the database fields being queried are NOT NULL.</p>
  
  <p>I cannot reproduce this error in dev environment. </p>
  
  <p>I think, that the reason this error happening in PROD, is because somehow, among the fields that are being queried, one is marked as NULL. I have no quick way of checking this, but I eventually will.</p>
  
  <p>My question for now is this: Could there be any other reason for this error? Is it possible to get this error if the query is as above, and the fields are indeed NOT NULLs. (And why?) If it is possible could you please provide an example how.</p>
  
  <p>Please only answer if you are positive that you are right, i.e. I need something stronger, than "I <em>think</em> this is so".</p>