gh9
gh9

Reputation: 10703

vb interfaces with linq-to-sql

I am having trouble with casting and interfaces. Below is the code I am using. What the error says. I dont fully understand what is going on. I thought that if i created a list of items which implement an interface, if i pass another item which also implements the interface then it should work. But it doesn't. Can someone explain why it doesn't and what I should do instead. Thank you very much

The error line has three astrix's to identify it. Again thank you very much

An unhandled exception of type 'System.InvalidCastException' occurred in DAL.dll

Additional information: Unable to cast object of type 'System.Data.Linq.DataQuery1[BuisnessObjects.Project]' to type 'System.Collections.Generic.IEnumerable1[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

Upvotes: 1

Views: 82

Answers (1)

Diego
Diego

Reputation: 20194

If you add a .Cast(Of BuisnessObjects.IProject) to the linq query it should work.

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

Upvotes: 1

Related Questions