Vb.net 从linq查询返回数据表
我试图从linq查询返回数据表,但收到错误消息。我正在VS2012中使用.net framework 4.0Vb.net 从linq查询返回数据表,vb.net,linq,Vb.net,Linq,我试图从linq查询返回数据表,但收到错误消息。我正在VS2012中使用.net framework 4.0 <Table> Public Class StaffOfficeAccess <Column(CanBeNull:=False, IsPrimaryKey:=True, IsDbGenerated:=True)> Public Property StaffOfficeAccessID As Int32 = 0 <Column> Public Prop
<Table>
Public Class StaffOfficeAccess
<Column(CanBeNull:=False, IsPrimaryKey:=True, IsDbGenerated:=True)>
Public Property StaffOfficeAccessID As Int32 = 0
<Column>
Public Property StaffID As Int32 = 0
<Column>
Public Property OfficeID As Int32 = 0
<Column(IsVersion:=True, IsDbGenerated:=True)>
Public Property Version As Byte()
End Class
“------错误------”
Public Function GetByStaffID(ByVal staffID As Int32) As DataTable
Dim query As IEnumerable(Of DataRow) = CType((From oa In db.StaffOfficeAccess.AsEnumerable() _
Join o In db.Office.AsEnumerable() On oa.OfficeID Equals o.OfficeID _
Select oa.OfficeID,
o.OfficeName), Global.System.Collections.Generic.IEnumerable(Of Global.System.Data.DataRow))
Dim table As DataTable = System.Data.DataTableExtensions.CopyToDataTable(query)
Return table
End Function
无法将类型为“d”的对象强制转换为类型为“System.Collections.Generic.IEnumerable`1[System.Data.DataRow]”的对象。
我在这里试过这个例子,但运气不好。在VS2012中,我没有获得CopyToDataTable。我已经尝试过这个方法,而且效果很好
<Table>
Public Class StaffOfficeAccess
<Column(CanBeNull:=False, IsPrimaryKey:=True, IsDbGenerated:=True)>
Public Property StaffOfficeAccessID As Int32 = 0
<Column>
Public Property StaffID As Int32 = 0
<Column>
Public Property OfficeID As Int32 = 0
<Column(IsVersion:=True, IsDbGenerated:=True)>
Public Property Version As Byte()
End Class
Dim dt As New DataTable()
dt.Columns.Add("OfficeID", GetType(Integer))
dt.Columns.Add("OfficeName", GetType(String))
Dim query = From oa In db.StaffOfficeAccess.AsEnumerable() _
Join o In db.Office.AsEnumerable() On oa.OfficeID Equals o.OfficeID _
Select oa.OfficeID,
o.OfficeName
For Each item In query
Dim dr As DataRow = dt.NewRow()
dr("OfficeID") = item.OfficeID
dr("OfficeName") = item.OfficeName
dt.Rows.Add(dr)
Next
另一种方法是使用
Aggregate
扩展方法
为什么它必须是DataTable?StatfficeAccess表没有office name实体。我需要返回办公室ID和办公室名称。可以是数据集,因为我需要用下拉列表控件绑定结果。