2

My function

public Permission[] GetPermissionsForGroupID(string groupID)
    {
        MySqlCommand command = new MySqlCommand();
        command.Connection = connection;
        command.CommandText = "SELECT `permissions`.`permissionName`, `groups_permissions`.`permissionValue` 
        FROM `db`.`groups_permissions`, `db`.`permissions` 
        WHERE `permissions`.`permissionID` = `groups_permissions`.`permissionID` 
        AND `groups_permissions`.`groupID` = '" + groupID + "'";
        MySqlDataReader reader = command.ExecuteReader();
        List<Permission> permissions = new List<Permission>();
        while (reader.Read())
        {
            permissions.Add(new Permission((string)reader[0], (int)reader[1]));
        }
        reader.Close();
        return permissions.ToArray();
    }

throws an System.InvalidCastException at

permissions.Add(new Permission((string)reader[0], (int)reader[1]));

I narrowed it down to (string)reader[0] where a varchar should be casted into a string.

reader[0] = permissions.permissionName = varchar

What could be the problem?

EDIT:

The value of reader[0] is a string "kick_user_power" and the value of reader[1] is an integer "75".

EDIT 2:

The constructor of Permission

public Permission(string permissionName, int permissionPower)
    {
        PermissionName = permissionName;
        PermissionPower = permissionPower;
    }

And, for better visualization, the values of reader[0] and reader[1]: Reader-Values

2
  • What is the value of reader[0], and, for that matter, of reader[1] ? Commented Mar 30, 2016 at 10:59
  • and the constructor for the Permission class - how does that look? Commented Mar 30, 2016 at 11:04

2 Answers 2

3

The dotnet SqlDataReader class includes functions for retrieving column data.

You probably want to use

   reader.GetString(0)

and

   reader.GetSqlInt32(1)

to retrieve your values.

In fact for best results you should use

  reader.IsDbNull(0)? "missing value" : reader.GetString(0)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice idea. I will definetly refactor my code to use this approach. It worked perfectly fine. Thank you!
0

Could it be that it's not the cast to string that is the issue, but the cast to int?
Try

permissions.Add(new Permission(reader[0].ToString(), Convert.ToInt64(reader[1])));

Both ToString() and Convert.ToInt64 are a bit less "sensitive".

1 Comment

Nope. It didn't work. I made sure it is reader[0] by separately assigning its values to variables. (I didn't show that in the question but mentioned it by saying that I narrowed it down to reader[0].)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.