linq

LINQ - Unable to cast object of type 'WhereListIterator1[UserView]' to type 'System.Collections.Generic.List1[UserView]'"


public IEnumerable<UserView> GetPageduserData(int deploymentId, UserViewSearchQuery searchQuery)
{
    try
    {

        ...
        return queryToReturn.Select(selector => new {
            selector.Id,
            selector.FirstName,
            PermissionLevelName = cultureCodeQuery.Where(x => x.UserView.Id == selector.Id).Select(x => x.Translation2Culture.Value).FirstOrDefault()
        }).AsEnumerable().Select(u => new UserView {
            Id = u.Id,
            FirstName = u.FirstName,
            PermissionLevelName = u.PermissionLevelName
        }).AsEnumerable();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        throw;
    }
}

Here is how it was called:

    Dim rowCollection = GetPageduserData(deploymentId, searchQuery).ToList()
    Dim count = rowCollection.Count

    If userIdFilter.Count > userIdFilterUsageTreshold Then
        rowCollection = rowCollection.Where(Function(x) userIdFilter.Contains(x.Id))
    End If

    If String.IsNullOrWhiteSpace(SocialSecurityFilter) = False AndAlso String.IsNullOrWhiteSpace(RFIDFilter) = False Then
        rowCollection = rowCollection.
                                    Where(Function(x) x.SocialSecurityNumber IsNot Nothing AndAlso
                                                        Crypto.BouncyCastleAesGCM.DecryptDatabaseData(x.SocialSecurityNumber).Contains(SocialSecurityFilter) AndAlso
                                                        x.RFID IsNot Nothing AndAlso
                                                        Crypto.BouncyCastleAesGCM.DecryptDatabaseData(x.RFID).Contains(RFIDFilter)
                                                    ).ToList()

    ElseIf String.IsNullOrWhiteSpace(SocialSecurityFilter) = False Then
        rowCollection = rowCollection.
                        Where(Function(x) x.SocialSecurityNumber IsNot Nothing AndAlso
                                    Crypto.BouncyCastleAesGCM.DecryptDatabaseData(x.SocialSecurityNumber).Contains(SocialSecurityFilter)
                            ).ToList()

    ElseIf String.IsNullOrWhiteSpace(RFIDFilter) = False Then
        rowCollection = rowCollection.
            Where(Function(x) x.RFID IsNot Nothing AndAlso
                Crypto.BouncyCastleAesGCM.DecryptDatabaseData(x.RFID).Contains(RFIDFilter)
            ).ToList()
    End If

Sometimes I got run-time error, sometimes I cannot even reproduce it, is there anything wrong with my code?


Solution

  • The reason may be here

    If userIdFilter.Count > userIdFilterUsageTreshold Then
            rowCollection = rowCollection.Where(Function(x) userIdFilter.Contains(x.Id))
    

    because you directly set Where return list to List<UserView> type variable. This will resolve if you use .ToList(). Other places you have done this correctly.