1

Why would this code generate null exception:

Public Function MessageCount(ByVal mId As Long) As Integer
    Dim messages As List(Of InboxMessage) = Nothing
    Using ctx As New UFCWEntities.UFCWEntities

        Dim allMessageIds = ctx.InboxLinks.Where(Function(o) o.MemberId = mId).ToList()
        For Each i As InboxLink In allMessageIds
            messages.Add(ctx.InboxMessages.FirstOrDefault(Function(o) o.InboxMessageId = i.InboxMessageId))
        Next

    End Using

    If Not IsNothing(messages) Then
        Return messages.Count()
    End If

    Return 0

End Function

Exception is generated when trying to do messages.Add

1

2 Answers 2

1

You're getting this error because ctx.InboxMessages.FirstOrDefault(...) is returning null.

You should be null checking first, e.g.:

For Each i As InboxLink In allMessageIds
    Dim firstMsg = ctx.InboxMessages.FirstOrDefault(...)
    If Not IsNothing(firstMsg) Then
        messages.Add(firstMsg)
    End If
Next
Sign up to request clarification or add additional context in comments.

1 Comment

To give more context, There is no item in InboxMessages which matches i.InboxMessageId.
0

You aren't instantiating your messages variable thus when you try to Add to it, it can't because messages is still Nothing. Change the first line to

Dim messages As New List(Of InboxMessage)

That being said, you may want to consider thinking about the whole operation as a set based operation. You shouldn't need to hydrate objects if all you want to do is filter them down and count the filtered results. From the code you supplied, you should be able to simplify this to:

Using ctx As New UFCWEntities.UFCWEntities
   return ctx.InboxLinks.Count(function(o) o.MemberId = mId)
End Using

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.