我是.NET新手,但需要深入遊一點。我的任務是擴展現有的單元測試,目前只是試圖接收所有存儲過程的列(作爲測試數據庫連接和模式的完整性的一種手段)。目標是檢索所有存儲過程的參數,並嘗試使用空值運行它們,進行測試以驗證沒有記錄集被返回。我一直在靠牆試圖加快ADO.NET的速度,但無法爲我的生活弄清楚如何做到這一點。這就像我已經得到的那樣(在某種程度上取消了上下文)。該測試抱怨說沒有參數被傳入,但我認爲我將現有參數設置爲null,並簡單地將其傳回。sqlCommand並以編程方式檢索和設置存儲過程的參數
// bind our sql schema gridview
foreach (SqlSchemaItem item in items)
{
// pull a connection
using (var sqlConnection = new SqlConnection(connectionString))
{
// open connection
sqlConnection.Open();
// get schema
try
{
/*
* Part 1 - test that the schema is ok...
*/
var sqlCommand = new SqlCommand(item.ObjectName, sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(sqlCommand);
sqlCommand.ExecuteReader(CommandBehavior.SchemaOnly);
// success to console
Console.WriteLine(item.ObjectName + " is ok.");
/*
* Part 2 - test that the stored procedure does not return any data.
*/
// set all the parameters to NULL
foreach (SqlParameter parameter in sqlCommand.Parameters)
{
if (parameter.Direction == ParameterDirection.Input || parameter.Direction == ParameterDirection.InputOutput)
{
parameter.Value = null;
Console.WriteLine("Parameter {0} set to null", parameter.ParameterName, parameter.Value);
}
}
var temp = sqlCommand.ExecuteReader(CommandBehavior.SingleResult);
if (temp.HasRows) {
Console.WriteLine(string.Format("A record was returned in {0} with value {0}", temp.GetName(0), temp.GetString(0)));
}
else {
Console.WriteLine("No result was returned");
}
Console.WriteLine(" ");
}
catch ...
finally ...
etc.
您是否嘗試過DbNull.Value而不是null? – Rytmis 2012-01-27 22:59:10
好的電話,謝謝。 (請參閱下面的回覆。) – DuncanMack 2012-01-29 18:14:53