.Net Core 读取 SQL 数据库 return 空值

.Net Core reading SQL database return null values

首先,请记住我是 .net 核心的新手。我正在尝试从 sql db 读取数据,但是对于字符串,我得到的是空值,对于整数,我得到的值是 0。

有趣的是,我得到了包含 5 个项目的数组列表(因为 select 前 5 个),以及正确的列数,但正如我所说,所有值要么为 null 要么为 0...

    public List<Student> Index()
    {
        List<Student> students = new List<Student>();
        string connectionString = configuraton.GetConnectionString("DefaultConnection");

        string query = "SELECT TOP 5 * FROM tblStudents";

        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open();

                using (SqlDataReader reader = cmd.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        Student student = new Student();
                        students.Add(student);
                    }
                }
            }
        }

        return students;

    }

更清楚地说,这是我在达到断点时为学生得到的

  id = 0
  contactPerson = null
  contactPhone = null
  createdDate = {01.01.0001 12:00:00 AM}

您正在遍历 reader 中的所有值但没有将值保存到学生 class,这意味着您正在将空的 class 添加到 students 集合中

 while (reader.Read())
  {
    Student student = new Student();
    students.Add(student);
  }

而是使用这样的东西:

while (reader.Read())
      {
        Student student = new Student();
        student.Id = Convert.ToInt32(reader["Id"]);
        student.Name = Convert.ToString(reader["Name"]);
        students.Add(student);
      }

根据 Panagiotis Kanavos 的评论:您创建了空学生。您需要将 reader 字段映射到您的学生对象,例如:

while (reader.Read())
{
    Student student = new Student();
    student.id = (int)reader["Id"];
    student.contactPerson = (string)reader["ContactPerson"];
    students.Add(student);
}