异常:指定的转换无效 [英] Exception: Specified cast is not valid

查看:284
本文介绍了异常:指定的转换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类UserLoginInfo 
{
公共UserRole的角色;
公共字符串用户名;使用

公共静态UserLoginInfo FetchUser(用户名字符串,字符串密码)
{
(VAR连接= Utils.Database.GetConnection()),使用(VAR命令
=新的SqlCommand(SELECT [用户名],[密码],[作用] FROM [用户],其中[用户名] = @用户名,连接))
{
command.Parameters.AddWithValue(@用户名, 用户名);使用(VAR读卡器= Command.ExecuteReader却())
{

如果(读者== NULL ||!reader.Read()||!Utils.Hash.CheckPassword(用户名,密码(字节[])读卡器[密码]))
抛出新的异常()错误的用户名或密码。

返回新UserLoginInfo {用户名=(字符串)读卡器[用户名],角色=(UserRole的)阅读器[角色]};
}
}
}
}

当我把一个断点,并调试错误来源于此行

 返回
新UserLoginInfo
{
=用户名(串)阅读器[用户名],
角色=(UserRole的)阅读器[角色]
};



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



编辑:我怎么可以转换(串)阅读器[角色]来的UserRole ??

 公开枚举的UserRole 
{
的管理员,
维修保养,
的用户
}


解决方案

 角色=(UserRole的)阅读器[角色 ] 

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



编辑:关于你提到的更新问题,你可以这样做:

  VAR作用=(字符串)读卡器[角色]; 
UserRole的角色=(UserRole的)Enum.Parse(typeof运算(UserRole的),作用);

您可能需要一些额外的错误检查添加,如检查角色不为空。此外,解析枚举之前,你可以检查分析是有效使用 Enum.IsDefined


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.

这篇关于异常:指定的转换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆