0
votes

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.

2

2 Answers

0
votes

Try plain old object:

object[] idItems = db.Database.SqlQuery<object>(idQuery).ToArray();
long[] idItemsLong = new long[idItems.Length];
for (int i = 0; i < idItemsLong.Length; i++)
{
    idItemsLong[i] = Convert.ToInt64(idItems[i]);
}
0
votes

I got a solution working without dynamic types:

long[] idItems = new long[1];
long[] valueItems = new long[1];

try
{
    idItems = db.Database.SqlQuery<long>(idQuery).ToArray();
    valueItems = db.Database.SqlQuery<long>(valueQuery).ToArray();
}
catch (Exception e)
{
    int[] idItemsInt = db.Database.SqlQuery<int>(idQuery).ToArray();
    int[] valueItemsInt = db.Database.SqlQuery<int>(valueQuery).ToArray();
    idItems = new long[idItemsInt.Length];
    valueItems = new long[idItemsInt.Length];
    for (int i = 0; i < idItems.Length; i++)
    {
        idItems[i] = Convert.ToInt64(idItemsInt[i]);
        valueItems[i] = Convert.ToInt64(valueItemsInt[i]);
    }
}

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.