[RESOLVED]System invalid cast exception converting a var count into an int

I am doing an sql query that counts the total number of records in a table then I want to subtract that number but I am getting a casting error this is my code

   // The sql table only has 15 records and i'm getting the error on the limit
var sql = sqlConnection.Query<profile>("select count(ProfileID) from profiles");
                int limit = 100 - Convert.ToInt32(sql);

The actual error states

Unable to cast object of type ‘System.Collections.Generic.List`1[Mymodel.Models.profile]‘ to type ‘System.IConvertible’.

What would be a good solution to get this to work..

Hi,

your returning an objects instead of value, please get the value from sql and convert, before converting to int make your that your checking Null 

Thanks,

Sen

Thank you just did that and solved it. For anyone who might be wondering how to do it using dapper just simply do this

 var sql = sqlConnection.Query<profile>("select * from profiles").ToList();
               int? limit = 100 - Convert.ToInt32(sql.Count());

Leave a Reply