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 回答