System.InvalidCastException: The specified listing is not valid. error

I am working 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 userid is equal to a specific value using LINQ.

For 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 displays a System.InvalidCastException: Specified cast is not valid. 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 the red area of ​​the selection.

I do not know what I did wrong. Please, help.

+4
source share
2 answers

The most likely cause of an InvalidCastException is the line x.Field<Int32>("userid") . The extension method Field<T> will throw an InvalidCastException if the actual data type does not match the type that was passed to Field<T> . Therefore, if userid not Int32 , that would throw.

EDIT

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

 x.Field<UInt32>("userid") 
+4
source

Without looking at the data returned from your database, I can only assume that the following part of your LINQ is to blame:

 x.Field<Int32>("userid") 

Your userid column value is probably not int, would I put my money on it as NULL?

UPDATE . Can you confirm that this is not a field challenge that breaks? Just change your code to something like this without a field call:

 public int getCount(int usercode){ int count = 0; DataTable mytable = getAllRowsAndReturnAsDataTable(); // assigning a DataTable value to mytable. if (mytable.Rows.Count > 0) { count = mytable.AsEnumerable().Count(); // No WHERE function call so no casting. } return count; } 

You can also check which values ​​are returned by mytable.AsEnumerable () in the viewport, for example, to make sure everything looks right. If the above code works, then it initiates a field call. Find out which line cannot be passed to and from Int32.

If it is really NULL, there are several ways to solve this problem.

  • Make sure you are not returning NULL from the database query, in MySQL you can use IFNULL .
  • Use a type with a null value for the total passed in the field:

    where x.Field ("userid") == (Int32?) usercode

0
source

Source: https://habr.com/ru/post/1498750/


All Articles