Tip: Never Orphan a Collection in NHibernate

Some guidelines on how to deal with a collection property in NHibernate:

  • Create a protected empty constructor for the use of NHibernate.  There should be no code in this constructor.
  • Create public constructors with parameters to allow you to create objects within your code.  These should initialize the collection properties, typically as empty collections.  (Use a simple List<T> until you’re more sophisticated.)
  • Never, ever, ever, set the collection property after construction.
  • Don’t allow it to have a public set.*
  • If you need to replace it, clear it and put the new values in.

Why is this so important?  Well, if you load the entity from the database, your collection property won’t be a List<T> anymore: it’ll be an object that NHibernate is using to track the one to many relationship.  If that exact object stops being connected to your entity, NHibernate will get upset and you can’t save your objects anymore. 

Unfortunately, people starting out tend to get an elevator pitch for NHibernate that suggest you can write your entities how you like and then it’ll just work.  That isn’t the case.  If you’re an NHibernate ninja, you’ll be able to break some of these guidelines.  But if you’re having problems, check that your entities follow them.

*Actually, I don’t tend to put public set on any entity.  This is part of my “make methods have names that explain the business process by which the entity changes” strategy.  But that’s a whole different blog post…

Technorati Tags:

Published by

Julian Birch

Full time dad, does a bit of coding on the side.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s