title: "Object reference not set to an instance of an object" - but nothing is null?
body: <p>Yeah, you probably think; "God, another one?". </p>
  
  <p>Yes, another one.</p>
  
  <blockquote>
    <p>"Object reference not set to an instance of an object."</p>
  </blockquote>
  
  <p>I've been working with EF6 lately and after developing for some time, I found that a little bit more optimization was needed. Alot has been reworked without problems, but it seems I can't figure out this one.</p>
  
  <p>In my application I've been using this piece of pseudo code to get items from the database.</p>
  
  <pre><code>DbContext context = new DbContext();
  
  public IEnumerable&lt;string&gt; GetExistingNames(IEnumerable&lt;string&gt; names)
  {
      foreach(string name in names)
      {
          string existingName = context.Names.Where(n =&gt; n.Name == name).FirstOrDefault();
          if(existingName == null) continue;
          yield return existingName;
      }
  }
  </code></pre>
  
  <p>Note that the <code>DbContext</code> is only there for clarification. It gets disposed when it's needed.</p>
  
  <p>This approach "works" but it would mean that if I had, say, 20 names to look up, I would hit the database for about 20 times. Ouch!</p>
  
  <p>Therefore I started looking for a way to implement a single query. I've found a way, but it's not really working as it should. This is my current approach;</p>
  
  <pre><code>public IEnumerable&lt;string&gt; GetExistingNames(ICollection&lt;string&gt; names)
  {
      IQueryable&lt;Names&gt; query = context.Names.Where(n =&gt; names.Contains(n.Name));
      if(query == null) yield break;
      foreach(var name in query)
      {
          yield return name.Name;
      }
  }
  </code></pre>
  
  <p>This should, to my knowledge, translate in <code>SELECT ... FROM Names WHERE ... IN (...)</code>. However, my application crashes at <code>foreach(var name in query)</code> as soon as it hits <code>name</code>, throwing the feared <code>NullReferenceException</code>.
  It does, however, pass <code>if(query == null)</code>, meaning the query is not null. At this point, I was confused. How can it not be null, but still throw this error?</p>
  
  <p>I was not sure if the query gets executed if I try to access it with this approach. Therefore, I tried to create a list from the query using <code>ToList()</code>, but this throws the same exception upon creating the list.</p>
  
  <p>It seems like everytime I make a call to <code>query</code>, it gives me a <code>NullReferenceException</code>. However, it still passes <code>if(query == null)</code>. So, my question is;</p>
  
  <p><strong>Why is it passing the test, but is it not accessible? Did I misinterpret <code>IQueryable&lt;&gt;</code>? And if I did misinterpret it, how should it be done properly?</strong></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have debugged before posting. I know for sure that;</p>
  
  <ul>
  <li><code>names</code> is not null.</li>
  <li><code>context</code> is not null.</li>
  </ul>
  
  <p>Code calling the function:</p>
  
  <pre><code>//A wrapper for the DbContext. This is only used for some methods
  //which require the DbContext
  DbContextWrapper wrapper = new DbContextWrapper();
  
  public void ProcessNames(List&lt;string&gt; inputNames)
  {
      //...
  
      foreach(string existingName in wrapper.GetExistingNames(inputNames))
      {
          //Do something with the names
      }
  
      //...
  }
  </code></pre>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>After some more debugging, I found that the query being created is somewhat different. It is supposed to be;</p>
  
  <pre><code>SELECT `Extent1`.`Name` 
  FROM `Names` AS `Extent1` 
  WHERE (`Extent1`.`Name` IN ( @gp1,@gp2))
  </code></pre>
  
  <p>However, I get this;</p>
  
  <pre><code>System.Data.Entity.Infrastructure.DbQuery&lt;MyDbContext.Names&gt;
  </code></pre>
  
  <p>As the actual query.</p>
  
  <p>The stack trace;</p>
  
  <pre><code>at MySql.Data.Entity.SqlGenerator.Visit(DbPropertyExpression expression)
  at MySql.Data.Entity.SqlGenerator.Visit(DbInExpression expression)
  at System.Data.Entity.Core.Common.CommandTrees.DbInExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
  at MySql.Data.Entity.SqlGenerator.VisitBinaryExpression(DbExpression left, DbExpression right, String op)
  at MySql.Data.Entity.SqlGenerator.Visit(DbAndExpression expression)
  at System.Data.Entity.Core.Common.CommandTrees.DbAndExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
  at MySql.Data.Entity.SelectGenerator.Visit(DbFilterExpression expression)
  at System.Data.Entity.Core.Common.CommandTrees.DbFilterExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
  at MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type)
  at MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type)
  at MySql.Data.Entity.SelectGenerator.Visit(DbProjectExpression expression)
  at System.Data.Entity.Core.Common.CommandTrees.DbProjectExpression.Accept[TResultType](DbExpressionVisitor`1 visitor)
  at MySql.Data.Entity.SelectGenerator.GenerateSQL(DbCommandTree tree)
  at MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
  at System.Data.Entity.Core.Common.DbProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
  at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver)
  at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
  at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree)
  at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
  at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__6()
  at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;&gt;c__DisplayClass7.&lt;GetResults&gt;b__5()
  at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
  at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
  at System.Data.Entity.Core.Objects.ObjectQuery`1.&lt;System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator&gt;b__0()
  at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
  at MyNameSpace.DbContextWrapper.&lt;GetExistingNames&gt;d__1b.MoveNext() in c:~omitted~\DbContextWrapper.cs:line 70
  at MyNameSpace.NameProcessor.ProcessNames(List&lt;string&gt; inputNames) in c:~omitted~\NameProcessor.cs:line 60
  </code></pre>