2014-04-30 45 views
0

我創建了一個存儲過程以從表中獲取1行。DbDataReader返回null

spGetDepartment 
    @ID int 
AS 
BEGIN 
    SELECT [ID],[Name],[Description] 
    FROM tblDepartments 
    WHERE [ID] = @ID 

END 

當存儲過程在SQL中測試時,我得到了所需的結果。

當我嘗試從代碼(C#)調用存儲過程並調試頁面時,我可以看到讀取器正確填充,但在嘗試讀取它時,它會更改爲空值。 這是調用存儲過程的代碼。

public static Department GetDepartment(string ID) 
    { 
     Department Dept = new Department(); 

     DbCommand comm = DataAccess.CreateCommand(); 
     try 
     { 
      comm.CommandText = "spGetDepartment"; 
      // create a new parameter 
      DbParameter _ID = comm.CreateParameter(); 
      _ID.ParameterName = "@ID"; 
      _ID.Value = ID; 
      _ID.DbType = DbType.Int32; 
      comm.Parameters.Add(_ID); 
      comm.Connection.Open(); 
      DbDataReader rdr = comm.ExecuteReader(); 
      while (rdr.Read()) 
      { 
       Dept.DepartmentID = Convert.ToInt32(rdr["ID"].ToString()); 
       Dept.DepartmentName = rdr["Name"].ToString(); 
       Dept.Description = rdr["Description"].ToString(); 
      } 
      rdr.Close(); 
     } 
     catch (Exception ex) 
     { 
      Utilities.LogError(ex); 
     } 
     finally 
     { 
      comm.Dispose(); 
      comm.Connection.Close(); 
     } 
     return Dept; 
    } 
+0

只是要清楚,你是說'RDR [ 「ID」]'是返回null?或者是其他東西? –

+0

當調試器到達while(rdr.read())行時,它進入rdr.close()步驟。它不會進入while循環 – netgk07

回答

0

試試這個:

SqlDataReader rdr = comm.ExecuteReader(); 
if (rdr.HasRows) 
{ 
    reader.Read(); 
    Dept.DepartmentID = Convert.ToInt32(rdr["ID"].ToString()); 
    Dept.DepartmentName = rdr["Name"].ToString(); 
    Dept.Description = rdr["Description"].ToString(); 
    reader.Close(); 
} 
else 
{ //No data 
} 
+0

這樣做的訣竅我把while語句改成了像上面顯示的if語句。非常感謝你。 – netgk07

+0

高興地幫助:) – singhsac