title: LINQ ToDictionary System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.'
body: <p>Going bonkers here, but have a LINQ query that i want to convert to a Dictionary object, but getting a "System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.'" error when doing so, so I'm stumped. It only happens if I just want to use the Key and use a Product class as the value.</p>
  
  <pre><code>ProductsDataContext context = new ProductsDataContext();
  
  Dictionary&lt;int, Product&gt; result = context.Products.Where(x =&gt; x.ProductName.StartsWith("N")).ToDictionary(x =&gt; x.Prod_ID); 
  </code></pre>
  
  <p>The Prod_ID is an integer in the class and in the database. Nowhere should be converted to a string, so I'm stumped as to this error message.</p>
  
  <p>If I write it something like this:</p>
  
  <pre><code>Dictionary&lt;int, string&gt; result = context.Products.Where(x =&gt; x.ProductName.StartsWith("N")).ToDictionary(x =&gt; x.Prod_ID, x=&gt; x.ProductName)
  </code></pre>
  
  <p>It works fine and there is no data conversion error message (the Key is an integer as specified). I hadn't used this method before (w/LINQ to SQL), so I'm thinking that something is missing. (It works on non-SQL stuff)</p>
  
  <p>Tried the same code on a different table and have gotten results (no errors).
  Looks like the problem was with nulls in the Product table (varchar() nulls - so the error message is completely off - a bug, perhaps?)</p>
  
  <pre><code>    StylesDataContext context = new StylesDataContext();
  
      Dictionary&lt;int,Style&gt; results = context.Styles.Select(x =&gt; x).Where(x =&gt; x.style_name.EndsWith("d")).ToDictionary(x =&gt; x.style_id);
      foreach (KeyValuePair&lt;int, Style&gt; r in results)
      {
          Console.WriteLine("id: " + r.Key.ToString()  + "\tName: " + r.Value.style_name + "\tGUID: " + r.Value.style_bvin  );
      }
  </code></pre>