0

我在将 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

请有人指出我哪里出错了,以便我可以在一份声明中做到这一点?

4

2 回答 2

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
于 2013-01-30T20:13:42.673 回答
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

当然,您可以使用泛型来概括您的代码,但我决定用最简单易懂的解决方案来帮助您。

于 2013-01-30T20:14:09.143 回答