Mapping NHibernate collections one way

I encountered an issue with an NHibernate mapping today that took me a short while to solve so I thought I’d post here to remind myself in future.

I wanted to map a parent child relationship but only manage the persistence from the parent end. Here’s an example:

Blog -< Post

  public class Blog
        public Blog()

        public virtual int BlogId { get; set; }

        public virtual IList<Post> Posts { get; set; }

Which might have the following mappings:

The problem I was having was that saving the blog entity was causing a SQL exception complaining that BlogId wasn’t a nullable field on the Post table. In the end the fix was easy – remove the not null constraint!

The reason being that nhibernate likes to save the Post records first, then go back and update the foreign key values once it has saved the Blog entity.

Leave a Reply

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

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

Facebook photo

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

Connecting to %s