我創建了一個存儲過程以從表中獲取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;
}
只是要清楚,你是說'RDR [ 「ID」]'是返回null?或者是其他東西? –
當調試器到達while(rdr.read())行時,它進入rdr.close()步驟。它不會進入while循環 – netgk07