0

Web API を既存の asp.net ASPX サイトに追加しようとしています。

私が望むのは、(JSON または XML で) クエリの結果を返すことだけですが、エラーが発生します: タイプ 'System.Data.DataTable' のオブジェクトをタイプ 'System.Collections.Generic.IEnumerable` にキャストできません1[System.Web.UI.WebControls.Table]'.

...コードのFinally部分。

APIコントローラーの私のコードは次のとおりです。

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
4

2 に答える 2

2

答えは、単に関数のシグネチャを As EnumerableRowCollection に変更することだと思います。DataTable オブジェクトを取得して AsEnumerable() メソッドを使用すると、データ行のコレクションが EnumerableRowCollection として返されますが、EnumerableRowCollection として記述するだけで十分です。

于 2012-10-02T21:51:13.493 に答える
0

例外メッセージを見ると、DataRow コレクションを System.Web.UI.WebControls.Table の IEnumerable に変換できないことが示されています。

問題は、関数の署名です。

Public Function GetValues() As IEnumerable(Of Table)

それは次のようなものでなければなりません

Public Function GetValues() As IEnumerable(Of DataTable)
于 2012-05-19T17:46:27.260 に答える