InvalidOperationException:没有数据时读取的尝试无效。 (SQL)

时间:2011-06-12 16:59:17

标签: c# sql invalidoperationexception

    void ExecuteContent()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph");
     sb.Append(" FROM Users as u");
     sb.Append(" INNER JOIN Threads as t ON u.UsersID = t.UsersID");
     sb.Append(" Where @UsersID=t.UsersID");
     sb.Append(" ORDER BY t.Date DESC");


     using (SqlConnection conn = new SqlConnection(AnswerQuestion.connectionString))
     {
         conn.Open();
         SqlCommand sqlComm = new SqlCommand(sb.ToString(), conn);
        MembershipUser CurrentUser = Membership.GetUser();    
         Guid i = (Guid)CurrentUser.ProviderUserKey;
         sqlComm.Parameters.Add("@UsersID", SqlDbType.UniqueIdentifier).Value = i;
         SqlDataReader dr = sqlComm.ExecuteReader();

         UserName = dr["Name"].ToString();//The exception is thrown here
         Image = (Image) dr["Avatar"];
         ThreadTitle = dr["ThreadTitle"].ToString();
         ThreadParagraph = dr["ThreadParagraph"].ToString();
         Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString()); 
     }

}

我不明白为什么我明白了。我所要做的就是让最后一个发布帖子的人......我看了调试,事情看起来很好。我也查看了visual studio 2010中的sql server ..有数据,但不知怎的,它没有被读取并抛出异常...... :(

2 个答案:

答案 0 :(得分:2)

在访问值之前,您应该检查dr.Read():

if(dr.Read())
{
    UserName = dr["Name"].ToString();//The exception is thrown here
    Image = (Image) dr["Avatar"];
    ThreadTitle = dr["ThreadTitle"].ToString();
    ThreadParagraph = dr["ThreadParagraph"].ToString();
    Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
}

答案 1 :(得分:0)

你必须通过读者循环:

while(dr.Read())
{
    serName = dr["Name"].ToString();//The exception is thrown here
         Image = (Image) dr["Avatar"];
         ThreadTitle = dr["ThreadTitle"].ToString();
         ThreadParagraph = dr["ThreadParagraph"].ToString();
         Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString()); 
}
如果您只有一个结果

if(dr.Read())

和 您应始终使用以下内容围绕Reader:

using(dr)
{
    while(dr.Read())
    {
    }
}

在调用ToString();

之前,你应该做一些空检查
ThreadParagraph = dr["ThreadParagraph"] == null ? "" : dr["ThreadParagraph"].ToString();

以下是在代码中编写查询的小提示,请使用逐字:

var query = @"SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph 
    FROM Users as u 
    INNER JOIN Threads as t ON u.UsersID = t.UsersID 
    Where @UsersID=t.UsersID ORDER BY t.Date DESC";