Mark
Mark

Reputation: 7818

Trying to return data from the asp.net web api

I'm trying to add the web api to an existing asp.net ASPX site.

All I want is for it to return (in JSON or XML) the results of my query - however I get the error: Unable to cast object of type 'System.Data.DataTable' to type 'System.Collections.Generic.IEnumerable`1[System.Web.UI.WebControls.Table]'.

... at the Finally part of the code.

My code in the API controller is:

Imports System.Web.Http
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient

Public Class ValuesController
Inherits ApiController

' GET /api/<controller>
Public Function GetValues() As IEnumerable(Of Table)

    Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=inv;Integrated Security=True")
    Dim cmd As SqlCommand = New SqlCommand("select * from customers", con)
    cmd.CommandType = CommandType.Text
    Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
    Dim dt As New DataTable
    Using con
        Try
            con.Open()
            adapter.Fill(dt)
            'Check if any rows were returned
            If dt.Rows.Count = 0 Then
                'If no rows, return nothing
                Return Nothing
            Else
                'Return the filled datatable
                Return dt
            End If
        Catch ex As Exception
            con.Close()
            Throw ex
        Finally
            con.Close()
        End Try
    End Using

    Return New String() {"value1", "value2"}
End Function

Upvotes: 0

Views: 2353

Answers (2)

software.salt
software.salt

Reputation: 21

I think the answer is simply to change the signature of your function to As EnumerableRowCollection. When you take a DataTable object and use the AsEnumerable() method, it returns a collection of datarows as EnumerableRowCollection, although it is sufficient to just write it as EnumerableRowCollection.

Upvotes: 2

Julien Jacobs
Julien Jacobs

Reputation: 2629

Look at the exception message, it says that it cannot convert a DataRow collection to IEnumerable of System.Web.UI.WebControls.Table.

The problem is the signature of your function.

Public Function GetValues() As IEnumerable(Of Table)

It should be something like

Public Function GetValues() As IEnumerable(Of DataTable)

Upvotes: 0

Related Questions