ARTICLE AD BOX
I have written code using ADO.NET to connect to SQL Server with Razor page (ASP.NET Core). The code looks correct, but the compiler keeps throwing the following error:
System.NullReferenceException: Object reference not set to an instance of an object
I use this code:
public class Student { public int Id; public string Name; } public class IndexModel : PageModel { public List<Student> StudentList = new List<Student>(); public void OnGet() { SqlConnection conn = new SqlConnection(@"Server=MYPC\SQLEXPRES; Database = studentDB; Trusted_Connection = True; TrustServerCertificate = True"); string sql = "SELECT Id, Name FROM Student"; SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Student stu = new Student(); stu.Id = Convert.ToInt32(rdr["Id"]); stu.Name = rdr["Name"].ToString(); StudentList.Add(stu); } conn.Close(); } }First I used ASP.NET Core 6, and I got this error, but when I use the same code in ASP.NET Core 10, it works fine.
What is the reason for this different behaviour?
