我正在尝试使用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列表.我做错了吗?
解决方法
首先,在(reader.Read())循环中,您不会在列表中添加任何内容. GetRecords和GetRecords2上都缺少Add方法调用:
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(); – 当程序流使用块退出时,它将自动完成,作为dispose方法的一部分.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。