2012-01-27 82 views
2

我是.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. 
+1

您是否尝试过DbNull.Value而不是null? – Rytmis 2012-01-27 22:59:10

+0

好的电话,谢谢。 (请参阅下面的回复。) – DuncanMack 2012-01-29 18:14:53

回答

2

使用DBNull.Value而不是null

+0

啊,宾果。我在想我的语法(或方法)是错误的,它并没有发生在我身上,我的空值实际上可能不为null。 – DuncanMack 2012-01-29 18:14:22

相关问题