【问题标题】:ASP.NET Web API List All Records from SQL Server TableASP.NET Web API 列出 SQL Server 表中的所有记录
【发布时间】:2017-12-14 21:46:16
【问题描述】:

我正在尝试按照一个简单的示例(下面的链接)来学习 Web API,但无法从我的基础表中列出所有记录。下面只会列出调用api时表中的最后一条记录。

    <HttpGet>
    Public Function GetEmployees() As Employee
        Dim reader As SqlDataReader = Nothing
        Dim myConnection As SqlConnection = New SqlConnection()
        myConnection.ConnectionString = "myconnectionstring"
        Dim sqlCmd As SqlCommand = New SqlCommand()
        sqlCmd.CommandType = CommandType.Text
        sqlCmd.CommandText = "Select * from tblEmployee"
        sqlCmd.Connection = myConnection
        myConnection.Open()
        reader = sqlCmd.ExecuteReader()
        Dim emp As Employee = Nothing
        While reader.Read()
            emp = New Employee()
            emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
            emp.Name = reader.GetValue(1).ToString()
            emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
        End While

        Return emp
        myConnection.Close()
    End Function

我尝试将函数类型更改为以下类型,但出现错误“无法将 'Employee' 类型的对象转换为类型 'System.Collections.Generic.IEnumerable”

 Public Function GetEmployees() As IEnumerable(Of Employee)

感谢原始教程: http://www.c-sharpcorner.com/UploadFile/97fc7a/webapi-restful-operations-in-webapi-using-ado-net-objects-a/

【问题讨论】:

  • 您需要一个通用列表 List。然后,您将在循环中添加一个新的单个实例。

标签: asp.net sql-server vb.net asp.net-web-api


【解决方案1】:

在您提供的代码中,您正在创建一个类型为“Employee”的变量“emp”。您的“While”循环执行并在每次迭代时不断重置“emp”变量。您需要一个员工集合,而不是使用单个变量--

Public Function GetEmployees() As List(Of Employee)
    Dim reader As SqlDataReader = Nothing
    Dim myConnection As SqlConnection = New SqlConnection()
    myConnection.ConnectionString = "myconnectionstring"
    Dim sqlCmd As SqlCommand = New SqlCommand()
    sqlCmd.CommandType = CommandType.Text
    sqlCmd.CommandText = "Select * from tblEmployee"
    sqlCmd.Connection = myConnection
    myConnection.Open()
    reader = sqlCmd.ExecuteReader()
    Dim empList As New List(Of Employee)()
    While reader.Read()
        Dim emp As Employee = New Employee()
        emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
        emp.Name = reader.GetValue(1).ToString()
        emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
        empList.Add(emp)
    End While

    myConnection.Close()
    Return empList
End Function

总结变化--

  • 函数应该返回一个员工列表而不是单个员工对象
  • 在每个循环中创建一个新员工,填充它,然后将其添加到列表中
  • 返回前关闭连接
  • 返回列表

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 2021-07-12
    • 2013-04-08
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多