views:

119

answers:

2

Should a lazy loaded collection in NHibernate ever give me a NullReferenceException? I'm getting an exception in a method like the following:

public void Test(ISession session, int id)
{
    var entity = session.Load<MyEntity>(id);
    entity.LazyLoadedCollection.Add(SomeItem);
}

The call to LazyLoadedCollection is throwing. My mapping looks like:

<bag lazy="true" table="MyTable">
  <key>
    <column name="LazyLoadedCollection" />
  </key>
  <many-to-many class="LazyLoadedItem">
    <column name="LazyLoadedItemId" />
  </many-to-many>
</bag>

Is this the expected behavior in NHibernate?

A: 

No it's not. This is a not a good way to ask a question on the internet.

And it's really impossible to give you a direction what to do if you don't post the code throwing the exception and tell us where the exception comes from.

Paco
Like I said in the post, the exception comes from calling entity.LazyLoadedCollection.Add. I really don't understand why the code following the exception matters. I'm getting an instance of my entity calling Session.Load and trying to add an object to a property on it that is a collection that is lazy loaded. Can you tell me what part of that is not clear?
Nathan Roe
The code in the entity class. I'm sure exception is not caused by NHibernate but by something else I don't see in your code example. What will happen when you do new Entity().LazyLoadedCollection.Add() without any mapping or reference to NHibernate? I guess the same, but I don't know how you implemented it.
Paco
+2  A: 

It's hard to say without seeing your class, but one thing you may not have realized is that you need to populate each collection in your class's constructor.

NHibernate will replace these collections with its own at certain times, but you still need to make sure they're initially populated with a HashedSet<T>, List<T>, or something else depending on the interface you're using.

Kyralessa