繁体   English   中英

例外:指定的演员表无效

[英]Exception: Specified cast is not valid

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"] };
            }
        }
    }
}

当我放置一个断点并调试错误来自这一行

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

我不明白为什么我会收到这个错误。 请帮我!

编辑:如何将(字符串)阅读器[“角色”]转换为UserRole?

public enum UserRole
{
    Admin,
    Maintance,
    User
}
Role = (UserRole)reader["Role"]

据推测, UserRole是您定义的类型,因此SqlDataReader不知道如何将从数据库获取的数据转换为此类型。 数据库中此列的类型是什么?

编辑:至于您更新的问题,您可以这样做:

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

您可能希望添加一些额外的错误检查,例如检查该role不为空。 此外,在解析枚举之前,您可以使用Enum.IsDefined检查解析是否有效。

(UserRole)reader["Role"]应该是(string)reader["Role"] SQL Server中没有UserRole类型。

代码可能失败了:

Role = (UserRole)reader["Role"];

因为您正在尝试将object UserRole转换为UserRole ,并且转换不存在。

看起来你正试图将 reader["Role"] UserRole转换为 UserRole对象,我猜这是失败的。

您需要指定(或实现)有效的强制转换,或者实现类似UserRole.Parse(string value)以将字符串解析为有效的UserRole对象。

如果您在数据库中存储的是一个string ,但是您想将其转换为enum类型,那么您应该使用Enum.Parse()方法

例如:

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

可能(UserRole)Enum.Parse(typeof(UserRole), (string) reader["Role"])是最受欢迎的答案,而且,令我惊讶的是,它的确有效! (令人惊讶的是,Enum.Parse方法正确地将整数的字符串表示转换为其对应的枚举值,考虑到数据库中的枚举值存储为整数)。 但这是我经常做的事情,要点到这一点:

UserRole role = (UserRole)Convert.ToInt32(reader["Role"]);

这应该更有效率,但在现实生活中没有明显的迹象。

这意味着你要么不能投射(string)reader["Username"] (不太可能),要么(UserRole)reader["Role"] (更有可能)。 什么是UserRole - 您可以通过从db结果转换来创建它吗? 你不需要new UserRole(reader["Role"])吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM