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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With