title: Entity Framework 5 database first - null reference in production only
body: <p>I've been using EF5 db first for some time in a .net 4.5 web project, and it's working well. </p>
  
  <p>I have one query that throws a null reference when calling Count() or ToList() or Any() etc.</p>
  
  <pre><code>        lastQuery =  dbContext.Set&lt;T&gt;();
          logger.Info("last Query: {0}", lastQuery); // this shows the correct query 
          lastQuery.ToList(); // only when the query is executed, null reference is thrown
  </code></pre>
  
  <p>lastQuery.ToString() shows the correct db query. </p>
  
  <p>this code works from localhost, dev, qa, and localhost pointing to uat/prod database. </p>
  
  <p>entity framework 5 assembly (EntityFramework.dll 5.0.0.net45) is included in deployment and referenced locally. </p>
  
  <p>It only breaks when this code is run on uat/prod server. </p>
  
  <p>it was my suspicion that asp.net mvc 4 was not up to date, so i deployed a standalone install, but that didn't fix it. </p>
  
  <p><strong>looking for ideas on how else to troubleshoot it, or what components may be missing in prod etc..</strong>  </p>
  
  <p><em>call stack:</em></p>
  
  <pre><code>System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.EntityKey.ValidateTypeOfKeyValue(MetadataWorkspace workspace, EdmMember keyMember, Object keyValue, Boolean isArgumentException, String argumentName)
   at System.Data.EntityKey.ValidateEntityKey(MetadataWorkspace workspace, EntitySet entitySet, Boolean isArgumentException, String argumentName)
   at System.Data.Objects.ObjectStateManager.CheckKeyMatchesEntity(IEntityWrapper wrappedEntity, EntityKey entityKey, EntitySet entitySetForType, Boolean forAttach)
   at System.Data.Objects.ObjectStateManager.AddEntry(IEntityWrapper wrappedObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
   at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
   at lambda_method(Closure , Shaper )
   at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
  </code></pre>