Home > OS >  Error - 'Unable to cast object of type 'System.Collections.Generic.List`1[]' to type
Error - 'Unable to cast object of type 'System.Collections.Generic.List`1[]' to type

Time:10-16

I am new to API's and I am developing one (trying to) in VB.net and have followed this video - https://www.youtube.com/watch?v=nMGlaiNBbNU. although I am using Visitors instead of employees.

I have translated the code to this - (From C# To VB)

Namespace Controllers
    Public Class VisitorsController
        Inherits ApiController

        Public Function [Get]() As IEnumerable(Of Visitor)
            Using entities As SignInSystemLiveEntities = New SignInSystemLiveEntities()
                Return entities.pa_Visitors_GetOnSite.ToList()
            End Using
        End Function
    End Class
End Namespace

although when i execute this i get the following error message:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List1[VisitorsDA.pa_Visitors_GetOnSite_Result]' to type 'System.Collections.Generic.IEnumerable1[VisitorsDA.Visitor]'.'

Please Help

Many Thanks,

CodePudding user response:

The List<T> class does implement the IEnumerable<T> interface, so that's not the problem. The issue is the item type. As the error message says, the method is supposed to return a list of VisitorsDA.Visitor objects but you're actually trying to return a list of VisitorsDA.pa_Visitors_GetOnSite_Result objects. Either get different objects to return or change the return type of the method, or else map the data between those two types somehow.

  • Related