2012-05-18 64 views
0

我試圖將web api添加到現有的asp.net ASPX站點。試圖從asp.net web api返回數據

所有我想要的是爲它返回(以JSON或XML)我的查詢結果 - 但是我得到的錯誤:無法投入'System.Data.DataTable'類型的對象鍵入'System.Collections。 Generic.IEnumerable`1 [System.Web.UI.WebControls.Table]」。

...在代碼的最後部分。

我在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 
+0

嘗試返回dt.AsEnumerable() – Brij

+0

嗨 - 不幸的是,也沒有工作 - 異常顯示:無法投型'System.Data.EnumerableRowCollection'1 [System.Data.DataRow]類型的對象類型'System.Collections.Generic.IEnumerable'1 [System.Web.UI.WebControls.Table]'。再次感謝,馬克 – Mark

回答

0

看看異常信息,它說,它不能一個DataRow集合轉換成System.Web.UI.WebControls.Table的IEnumerable的。

問題是你的函數的簽名。

Public Function GetValues() As IEnumerable(Of Table) 

它應該是這樣的

Public Function GetValues() As IEnumerable(Of DataTable) 
+0

嗨,感謝您的建議 - 我改變了這一點,目前的錯誤建議:無法投入類型'System.Data.EnumerableRowCollection'1 [System.Data.DataRow]'的對象鍵入'System.Collections .Generic.IEnumerable'1 [System.Data.DataTable]」。 - 謝謝 – Mark

+0

嘗試使用IEnumerable(Of DataRow),因爲這真的是底層類型 –

2

我認爲答案很簡單,就是你的函數的簽名更改爲作爲EnumerableRowCollection。當您使用DataTable對象並使用AsEnumerable()方法時,它將返回一組數據行作爲EnumerableRowCollection,儘管只需將其編寫爲EnumerableRowCollection即可。