2

getRecords のリストで getRecords2 のリストを追加しようとしています。getRecords でなぜか処理に時間がかかり、呼び出すとタイムアウトしてしまいます。

public static List<ListA> getRecords2(string id)
{
   List<ListA> listOfRecords = new List<ListA>();
   using (SqlConnection con = SqlConnect.GetDBConnection())
   {
      con.Open();
      SqlCommand cmd = con.CreateCommand();
      cmd.CommandText = "sp2";
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.Add(new SqlParameter("@id", id));

      SqlDataReader reader = cmd.ExecuteReader();

      while (reader.Read())
      {
         ListA listMember = new ListA();
         listMember.ID = (int)reader["ID"];
     listMember.Name = reader["FullName"].ToString().Trim();
      }
      con.Close();
    }
       return listOfRecords;
  }

  public static List<ListA> getRecords(string id)
  {
     List<ListA> listOfRecords = new List<ListA>();
     using (SqlConnection con = SqlConnect.GetDBConnection())
     {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "sp1";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@id", id));

        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
           ListA listMember = new ListA();
           listMember.ID = (int)reader["ID"];
           listMember.Name = reader["FullName"].ToString().Trim();
        }
        con.Close();
      }
      List<ListA> newlist = getRecords(id);
      foreach (ListA x in newlist) listOfRecords.Add(x);
      return listOfRecords;
   }

getRecords2 に getRecords のリストを追加します。私はそれを間違っていますか?

4

1 に答える 1

7

while(reader.Read())まず第一に、ループ内でリストに何も追加していません。と の両方でAddメソッド呼び出しがありません:GetRecordsGetRecords2

    while (reader.Read())
    {
        ListA listMember = new ListA();

        listMember.ID = (int)reader["ID"];
        listMember.Name = reader["FullName"].ToString().Trim();

        // you have to add this line:
        listOfRecords.Add(listMember);
    }

そして別の問題:あなたは何度も電話getRecords(id)をかけています:

List<ListA> newlist = getRecords(id);
foreach (ListA x in newlist) listOfRecords.Add(x);

次のようにする必要があります。

List<ListA> newlist = getRecords2(id);
foreach (ListA x in newlist) listOfRecords.Add(x);

そして最後になりましたが、呼び出す必要はありません。メソッドの一部として、con.Close();プログラムフローがブロックを終了すると自動的に呼び出されます。usingDispose

于 2013-04-10T19:46:19.100 に答える