I’m running a query in my ASP.NET MVC3 application to get some numbers from the database:
var idQuery = "SELECT " + dynamicColumnName + " FROM " + dynamicTableName;
long[] idItems = db.Database.SqlQuery<long>(idQuery).ToArray();
However, the dynamic column is sometimes int type int and sometimes long. I tried long as it covers int, but the program thrown the exception:
The specified cast from a materialized ‘System.Int32’ type to the ‘System.Int64’ type is not valid.
I tried the type dynamic but couldn’t get the numbers right:
dynamic[] idItems = db.Database.SqlQuery<dynamic>(idQuery).ToArray();
long[] idItemsLong = new long[idItems.Length];
for (int i = 0; i < idItemsLong.Length; i++)
{
idItemsLong[i] = Convert.ToInt64(idItemsLong[i]);
}
Throws the exception:
Unable to cast object of type ‘System.Object’ to type ‘System.IConvertible’.
What can I do to work my query run for both ints and longs? 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.
I got a solution working without dynamic types:
By this I get longs first, if type is int, than I get ints and convert them to long. If I had a dynamic type, I would always do conversion. So if my type is long (generally is), I am free of unnecessary conversion and I think this is faster.