I have an enum called ProfileType and in MySQL it is stored as an enum like this:
The problem is that once I try to login it crashes giving me a "specified cast is not valid" which happens when instatiating the Profile.
var cmd = new MySqlCommand($"select * from users where username='{username}' and password='{password}'", connection);
var rd = cmd.ExecuteReader();
if (rd.HasRows)
{
rd.Read();
return new Profile
{
Username = rd.GetString("username"),
Email = rd.GetString("email"),
Password = rd.GetString("password"),
Picture = rd.GetString("picture"),
ProfileType = (ProfileType)rd.GetInt16("profileType"),
AdditionalData = rd.GetString("additionalData")
};
This is the enum:
public enum ProfileType
{
User = 0,
Library = 1,
Admin = 2
}
I used int to store enum but it was always giving me ‘0’ even if I was signing up as a library.
2
Answers
Since "rd.GetFieldType("profileType").ToString()" is "System.String", you aren’t able to GetInt16 from it.
–>
MySQL
enum
types are actually returned as strings, so you need to parse itOr on older versions of .NET
Side notes on your code:
using
.if (rd.HasRows)
is unnecessary, you can get that fromrd.Read()