0

我有这个 sql 查询需要将 linq 转换为实体

select kv.KeyID, kv.KeyVotID, v.VotID, v.FullName
from E_KeyVot kv
join E_Vot v
on kv.VotID = v.VotID
where kv.KeyID=2
order by v.FullName

这是我尝试过的,但我确定它不正确:

Public Function GetKeyVot() As IQueryable(Of Ems_KeyVot)
  Try
     Dim _objQuery As IQueryable(Of Ems_KeyVot, Ems_Vot) = _
         From a In Context.Ems_KeyVot 
         Join b In Context.Ems_Vot On a.votid Equals b.votid
         Where a.keyid = pub_KeyID
         Order By b.FullName
     Return _objQuery
   Catch ex As Exception
   End Try
 End Function 
4

1 回答 1

0

根据您的查询,您遇到的问题是您的返回类型与查询不符。该查询返回一个 IQueryable(Of Ems_KeyVot, Ems_Vot),但您的函数需要一个 IQueryable(Of Ems_KeyVot)。

在您的查询中,您正在从两个表中投影值。由于您不能从函数中返回匿名类型,因此您需要创建另一个类来返回结果:

Public Class Votes
  Public Property KeyID As Integer
  Public Property KeyVotID As Integer
  Public Property VotID As Integer
  Public Property FullName As String
End Class

有了它,您可以按如下方式修改您的查询:

 Dim _objQuery As IQueryable(Of Ems_KeyVot, Ems_Vot) = _
     From a In Context.Ems_KeyVot 
     Join b In Context.Ems_Vot On a.votid Equals b.votid
     Where a.keyid = pub_KeyID
     Order By b.FullName
     Select New Votes With { .KeyID = a.KeyID, .KeyVotID = a.KeyVotID, .VotID = b.VotID, .FullName = b.FullName }

还将您的函数定义更改为

Public Function GetKeyVot() As IQueryable(Of Votes)

另一个注意事项,我看到你有一个 try catch 块,但你没有对异常做任何事情。如果您无法处理异常,请删除该块并让它冒泡到可以处理的地方。

于 2013-07-18T18:48:25.307 回答