我编写了以下代码来从SQL服务器中的表中提取所有记录。代码中没有错误,但是当我在fiddler中运行它时,我得到了空对象。
[HttpGet]
public List<Student> Get()
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = @"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from Tbl_Students;";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
int rowCount = 0;
while (reader.Read())
{
rowCount++;
}
Student[] student = new Student[rowCount];
for(int i=0;i<rowCount;i++)
{
student[i] = new Student();
}
int j = 0;
while (reader.Read())
{
// student[j] = new Student();
student[j].Roll_Number = Convert.ToInt32(reader.GetValue(0));
student[j].FirstName = reader.GetValue(1).ToString();
student[j].LastName = reader.GetValue(2).ToString();
student[j].Class = Convert.ToInt32(reader.GetValue(3));
student[j].Gender = reader.GetValue(4).ToString();
j++;
}
return student.ToList();
myConnection.Close();
}
我在表格中有5条记录。我能够获得5个json对象,但没有内容。
附加来自Fiddler的图像:
Student.cs
namespace WebAPIDemo.Models
{
public class Student
{
public int Roll_Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Class { get; set; }
public string Gender { get; set; }
}
}
答案 0 :(得分:1)
试一试,不计算记录数。我没有使用数组,我为每条记录创建了新的学生实例。
public static List<Student> GetData()
{
List<Student> lstStudent = new List<Student>();
using (SqlConnection con = new SqlConnection(@"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;"))
{
using (SqlCommand cmd = new SqlCommand("Select * from Tbl_Students;", con))
{
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Student student =new Student();
student.Roll_Number = Convert.ToInt32(reader.GetValue(0));
student.FirstName = reader.GetValue(1).ToString();
student.LastName = reader.GetValue(2).ToString();
student.Class = Convert.ToInt32(reader.GetValue(3));
student.Gender = reader.GetValue(4).ToString();
lstStudent.Add(student);
}
}
}
return lstStudent;
}
答案 1 :(得分:1)
您的第一个while(reader.Read())
是包含数据的实际读者对象。 DataReader
允许仅转发对数据行的只读访问。下一个while
循环甚至不会执行,因为Read()
已经完成。所以你得到一个5的数组{ {1}}使用默认值初始化的对象。
而不是初始化Student
个填充实例的数组,并添加到Student
循环内的List<Student>
。