gpt4 book ai didi

c# - while(reader.Read()) {} 中列表中的重复值

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:57 24 4
gpt4 key购买 nike

[WebMethod]
public List<reports> getMyReports( int user_id )
{
string cs = ConfigurationManager.ConnectionStrings["ReportDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getAllReportsByUserID", con);
cmd.CommandType = CommandType.StoredProcedure;
List<reports> repers = new List<reports>();
//users[][] liser = new users[][];
SqlParameter user_id_parameter = new SqlParameter("@user_id", user_id);
cmd.Parameters.Add(user_id_parameter);
reports report = new reports();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
}
}

我有调用以下存储过程的顶级函数:

CREATE Proc [dbo].[getAllReportsByUserID]
@user_id int
as
Begin
Select
id,
title,
description,
anonymous,
location,
status,
category,
date,
picture_url,
admin_id
from reports
where user_id = @user_id
End

我已经单独测试了该程序,它运行良好。然而,当我测试上面创建的 WebService 时,我得到一个列表,其中最后一个值在整个列表中重复。

谁能帮我弄清楚为什么我会一遍又一遍地重复相同的(最后的)值?

最佳答案

通过在循环之前创建报表对象并重复使用它,您可以在列表中多次插入对同一对象的引用。

您应该在循环内创建报告对象:

        SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
reports report = new reports();
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;

关于c# - while(reader.Read()) {} 中列表中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com