将Membership Provider从ODBC转换为SQL抛出异常

时间:2012-05-31 01:30:46

标签: c# asp.net sql membership-provider

我在调试reader = cmd.ExecuteReader();时遇到异常。

CS0266:无法将类型'System.IAsyncResult'隐式转换为'System.Data.SqlClient.SqlDataReader'。

这是从MSDN示例成员资格提供程序(http://msdn.microsoft.com/en-us/library/6tc47t75.aspx)派生的自定义MembershipProvider,其用户名值调用电子邮件数据库字段而不是单独的用户名输入,并且连接已从Odbc更改为SQL连接。

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("SELECT UserID, Email, PasswordQuestion," +
            " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
            " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +
            " FROM Users WHERE Email = ? AND ApplicationName = ?", conn);

        cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 128).Value = username;
        cmd.Parameters.Add("@ApplicationName", SqlDbType.NVarChar, 255).Value = m_ApplicationName;

        MembershipUser u = null;
        SqlDataReader reader = null;

        try
        {
            conn.Open();

            reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                u = GetUserFromReader(reader);

                if (userIsOnline)
                {
                    SqlCommand updateCmd = new SqlCommand("UPDATE Users " +
                        "SET LastActivityDate = ? " +
                        "WHERE Email = ? AND Applicationname = ?", conn);

                    updateCmd.Parameters.Add("@LastActivityDate", SqlDbType.DateTime).Value = DateTime.Now;
                    updateCmd.Parameters.Add("@Email", SqlDbType.VarChar, 255).Value = username;
                    updateCmd.Parameters.Add("@ApplicationName", SqlDbType.VarChar, 255).Value = m_ApplicationName;

                    updateCmd.ExecuteNonQuery();
                }
            }

        }

2 个答案:

答案 0 :(得分:1)

你试过在sqlcommand中指定参数名吗?问号似乎很奇怪

SqlCommand cmd = new SqlCommand("SELECT UserID, Email, PasswordQuestion," +
    " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
    " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +
    " FROM Users WHERE Email = @email AND ApplicationName = @applicationname", conn);

答案 1 :(得分:0)

您是否尝试过使用Dataadaptor而不是阅读器?您无论如何都没有正确关闭阅读器,这可能会导致您的网站出现内存问题。老实说,除了非常具体的情况,我几乎总是与读者有问题。