vb与linq-to-sql接口

时间:2011-03-01 17:53:38

标签: .net linq

我在使用转换和界面时遇到问题。以下是我正在使用的代码。错误说的是什么。我不完全明白发生了什么。我想如果我创建了一个实现接口的项目列表,如果我传递另一个也实现接口的项目,那么它应该工作。但事实并非如此。有人可以解释为什么它没有,我应该做什么。非常感谢你

错误行有三个astrix来识别它。再次非常感谢你

  

未处理的类型异常   发生'System.InvalidCastException'   在DAL.dll中

     

其他信息:无法投射   对象类型   'System.Data.Linq.DataQuery 1[BuisnessObjects.Project]' to type 'System.Collections.Generic.IEnumerable 1 [BuisnessObjects.IProject]'

Imports BuisnessObjects
Public Class ProjectInfoRepository
    Implements IProjectInfoRepository
             Function GetAllProjects() As List(Of BuisnessObjects.IProject) Implements IProjectInfoRepository.GetAllProjects
        Dim returnList As New List(Of BuisnessObjects.IProject)
        ***returnList.AddRange(From p In DC.ProjectInfos _
                          Select New BuisnessObjects.Project() With {.ProjectID = p.projectID, .ProjectName = p.projectName})***

        Return returnList
    End Function
End Class


Public Class Project
    Implements IProject
    Private _projectName As String
    Property ProjectName() As String Implements IProject.ProjectName
        Get
            Return _projectName
        End Get
        Set(ByVal value As String)
            _projectName = value
        End Set
    End Property
    Private _projectID As Integer
    Property ProjectID() As Integer Implements IProject.ProjectID
        Get
            Return _projectID
        End Get
        Set(ByVal value As Integer)
            _projectID = value
        End Set
    End Property
End Class


Public Interface IProject
    Property ProjectName() As String
    Property ProjectID() As Integer
End Interface

1 个答案:

答案 0 :(得分:1)

如果您向linq查询添加.Cast(Of BuisnessObjects.IProject),它应该可以正常工作。

Function GetAllProjects() As List(Of BuisnessObjects.IProject) Implements IProjectInfoRepository.GetAllProjects
        Dim returnList As New List(Of BuisnessObjects.IProject)

        returnList.AddRange((From p In DC.ProjectInfos _
                            Select New BuisnessObjects.Project() With {.ProjectID = p.projectID, .ProjectName = p.projectName}).Cast(Of BuisnessObjects.IProject))

        Return returnList
End Function