System.InvalidCastException: Specified cast is not valid. Error

asp.net, c#, linq, mysql

Solution

The most likely cause of the `InvalidCastException` is the `x.Field<Int32>("userid")` line. The `Field<T>` extension method will throw an `InvalidCastException` in the case where the actual type of the data doesn't match the type which was passed to `Field<T>`. Hence if `userid` wasn't an `Int32` this would throw.

EDIT

Based on your comments the type of `userid` is actually `UInt32` and not `Int32`. This is what is causing the problem. Try using the following and it should work

x.Field<UInt32>("userid")

Problem

I am on a C# ASP.NET project. I have a MySQL table with a userid field of type `int`. Now I want to get the number of rows where value of userid equals certain value using LINQ. To achieve this, I wrote the following method: ``` public int getCount(int usercode) { int count = 0; DataTable mytable = getAllRowsAndReturnAsDataTable(); // assigning a DataTable value to mytable. if (mytable.Rows.Count > 0) { count = (from x in mytable.AsEnumerable() where x.Field<Int32>("userid") == usercode select x).Count(); } return count; } ``` but it is showing error `System.InvalidCastException: Specified cast is not valid.` showing `count = (from x in mytable.AsEnumerable() where x.Field<Int32>("userid") == usercode select x).Count();` in red highlight area. I don't know what I did wrong here. Please help.

Original source