如何在 C# 中使用存储过程和数据读取器 return 记录列表

How to return list of records using stored procedure and datareader in C#

我想 return 在 C# 中使用存储过程和数据读取器的记录列表。目前,它给我错误

Cannot implicitly convert type 'ClsHorseTracker' to 'System.Collections.Generic.List'

代码:

public List<ClsHorseTracker> HorseTrackerList()
{
    clsUtilities clsUtilities = new clsUtilities();
    DataSet ds;
    List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();

    string sSQL = "exec HorseDetails";
    ds = clsUtilities.GetDataSet(sSQL);

    SqlCommand cmd = new SqlCommand();

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                clsHorseTracker = new ClsHorseTracker
                    {
                        HorseName = Convert.ToString(reader["HorseName"]),
                        HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
                    };
            }
        }
    }

    return clsHorseTracker;
}

clsHorseTracker 是 ClsHorseTracker 的列表。因此,您需要在 "while" 循环中将新对象添加到列表中,而不是将对象分配给列表 试试这个

public List<ClsHorseTracker> HorseTrackerList()
        {
         clsUtilities clsUtilities = new clsUtilities();
           DataSet ds;
           List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();

            string sSQL;
            sSQL = "exec HorseDetails";
            ds = clsUtilities.GetDataSet(sSQL);

            SqlCommand cmd = new SqlCommand();

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        clsHorseTracker.Add(new ClsHorseTracker
                        {

                            HorseName = Convert.ToString(reader["HorseName"]),
                            HorseTypeName = Convert.ToString(reader["HorseTypeName"]),

                        });
                    }
                }


            }


            return clsHorseTracker;
        }