title: ASP.NET MVC Dynamic Number Type
body: <p>I'm running a query in my ASP.NET MVC3 application to get some numbers from the database:</p>
  
  <pre><code>var idQuery = "SELECT " + dynamicColumnName + " FROM " + dynamicTableName;
  long[] idItems = db.Database.SqlQuery&lt;long&gt;(idQuery).ToArray();
  </code></pre>
  
  <p>However, the dynamic column is sometimes int type <code>int</code> and sometimes <code>long</code>. I tried <code>long</code> as it covers int, but the program thrown the exception:</p>
  
  <blockquote>
    <p>The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid.</p>
  </blockquote>
  
  <p>I tried the type <code>dynamic</code> but couldn't get the numbers right:</p>
  
  <pre><code>dynamic[] idItems = db.Database.SqlQuery&lt;dynamic&gt;(idQuery).ToArray();
  long[] idItemsLong = new long[idItems.Length];
  for (int i = 0; i &lt; idItemsLong.Length; i++)
  {
      idItemsLong[i] = Convert.ToInt64(idItemsLong[i]);
  }
  </code></pre>
  
  <p>Throws the exception:</p>
  
  <blockquote>
    <p>Unable to cast object of type 'System.Object' to type 'System.IConvertible'.</p>
  </blockquote>
  
  <p>What can I do to work my query run for both <code>int</code>s and <code>long</code>s? Ways of getting the dynamic type and converting them to long work for me, I can use the idItems as long in my following lines of code.</p>