我有使用ASP.net的Web API从SQL数据库检索信息的一些问题。的ASP.NET Web API - SQL - 检索信息
我曾尝试使用形式,这真是棒极了(使用GridView控件),但是当我尝试使用专用于存储我的特定表我得到这个错误一个单独的类来做到这一点:
“索引超出范围内,必须是非负值,并且小于集合的大小。“
这是代码:
public ActionResult Details()
{
List<Employee> employeeList = new List<Employee>();
string CS = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
using (var myConn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployee", myConn);
myConn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int i = 0;
employeeList[i].PersonID = Convert.ToInt32(rdr["PersonID"]);
employeeList[i].Name = rdr["Name"].ToString();
employeeList[i].Gender = rdr["Gender"].ToString();
employeeList[i].City = rdr["City"].ToString();
employeeList[i].DepartmentID = Convert.ToInt32(rdr["DepartmentID"]);
i++;
}
return View(employeeList);
}
}
这是Employee类:
[Table("tblEmployee")]
public class Employee
{
public int PersonID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DepartmentID { get; set; }
}}
我得到任何的检索信息的行此错误。
表有5列:是PersonID(INT PK),姓名(NVARCHAR),性别(NVARCHAR),市(NVARCHAR),DepartmentID的(INT)。
我查了很多次的列名,以确保我没有了那些错误,我仔细检查了连接字符串,这也是精(相同的代码可与使用gridview的形式API)。
希望有人能帮助我与此有关。我没有找到任何具体的信息,我想这应该很容易,我在这里做错了什么。
谢谢!它解决了我的问题 – Moshe