我在将LINQ语句输出到Visual Studio 2010中编写的ASP.NET列表时遇到问题。下面的函数尝试在其数据源中搜索相关的DVD并输出一条记录:
Public Function GetDVD(ByVal id As Integer) As DVDRaritiesDVDs _
Implements IDVDDAO.GetDVD
Dim DVD = From DVDList In _context.DVDRaritiesDVDs _
Where DVDList.DVDID = id Select DVDList
Return DVD.ToList().First()
End Function
但是当我尝试加入它时:
Public Function GetDVD(ByVal id As Integer) As DVDRaritiesDVDs _
Implements IDVDDAO.GetDVD
Dim DVD = From DVDList In _context.DVDRaritiesDVDs _
Join Category In _context.DVDRaritiesCategories _
On Category.CategoryID Equals DVDList.CategoryID _
Where DVDList.DVDID = id Select DVDList, Category
Return DVD.ToList().First()
End Function
在构建代码时,它给出了以下错误:
错误1类型'(第23行)'的值无法转换为'DVDRarities.Data.DVDRaritiesDVDs'。 C:\ Users \ a9010799 \ Projects \ DVDRarities \ DVDRarities.Data \ DAO \ DVDDAO.vb 24 16 DVDRarities.Data
请有人指出我出错的地方,所以我可以在一个声明中做到这一点吗?
答案 0 :(得分:0)
在您的查询中,您将针对DVDList实例返回{DVDList,Category}。 你应该使用
Public Function GetDVD(ByVal id As Integer) As DVDRaritiesDVDs _
Implements IDVDDAO.GetDVD
Dim DVD = From DVDList In _context.DVDRaritiesDVDs _
Join Category In _context.DVDRaritiesCategories _
On Category.CategoryID Equals DVDList.CategoryID _
Where DVDList.DVDID = id Select DVDList
Return DVD.First()
End Function
或者您应该更改此方法的签名。
Public Function GetDVD(ByVal id As Integer) As Tuple(Of DVDRaritiesDVDs, DVDRaritiesCategories) _
Implements IDVDDAO.GetDVD
Dim DVD = From DVDList In _context.DVDRaritiesDVDs _
Join Category In _context.DVDRaritiesCategories _
On Category.CategoryID Equals DVDList.CategoryID _
Where DVDList.DVDID = id Select New Tuple(Of DVDRaritiesDVDs, DVDRaritiesCategories)(DVDList, Category)
Return DVD.First()
End Function
答案 1 :(得分:0)
您的函数返回DVDRaritiesDVDs对象。显然你的Linq查询返回一个包含对的列表(DVDRaritiesDVDs,DVDRaritiesCategories)
您应该按以下方式更新代码:
Public Class Pair
Public First as DVDRaritiesDVDs
Public Second as DVDRaritiesCategories
End Class
Public Function GetDVD(ByVal id As Integer) As DVDRaritiesDVDs _
Implements IDVDDAO.GetDVD
Dim DVD = (From DVDList In _context.DVDRaritiesDVDs _
Join Category In _context.DVDRaritiesCategories _
On Category.CategoryID Equals DVDList.CategoryID _
Where DVDList.DVDID = id
Select New Pair() With {First = DVDList, Second = Category})
Return DVD.ToList().First()
End Function
当然,你可以使用泛型来概括你的代码,但我决定用最简单易懂的解决方案来帮助你。