Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception: Specified cast is not valid

Tags:

c#

casting

public class UserLoginInfo
{
    public UserRole Role;
    public string Username;

    public static UserLoginInfo FetchUser(string username, string password)
    {
        using (var connection = Utils.Database.GetConnection())
        using (var command = new SqlCommand("SELECT [Username], [Password], [Role] FROM [Users] WHERE [Username] = @username", connection))
        {
            command.Parameters.AddWithValue("@username", username);
            using (var reader = command.ExecuteReader())
            {
                if (reader == null || !reader.Read() || !Utils.Hash.CheckPassword(username, password, (byte[])reader["Password"]))
                    throw new Exception("Wrong username or password.");

                return new UserLoginInfo { Username = (string)reader["Username"], Role = (UserRole)reader["Role"] };
            }
        }
    }
}

When I put a breakpoint and debug the error comes from this line

return 
    new UserLoginInfo 
    { 
        Username = (string)reader["Username"], 
        Role = (UserRole)reader["Role"] 
    };

I don't understand why I get this error. Please help me!

EDIT: How can I convert (string)reader["Role"] to UserRole??

public enum UserRole
{
    Admin,
    Maintance,
    User
}
like image 541
Ivan Stoyanov Avatar asked Dec 07 '09 16:12

Ivan Stoyanov


1 Answers

Role = (UserRole)reader["Role"]

Presumably UserRole is a type you have defined, hence the SqlDataReader does not know how to convert the data it gets from the database to this type. What is the type of this column in your database?

EDIT: As for your updated question you can do:

var role = (string)reader["Role"];
UserRole role = (UserRole)Enum.Parse( typeof(UserRole), role );

You might want to add in some extra error checking, eg checking that role is not null. Also, before parsing the enum you could check if the parse is valid using Enum.IsDefined.

like image 86
Winston Smith Avatar answered Oct 12 '22 23:10

Winston Smith