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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Mar 19 '14 at 20:06

2 Answers2

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
Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
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
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43