NHibernate on .Net 2.0Part I

time to read 3 min | 500 words

I've been developing in .Net 2.0 [without ReSharper* :-( ], and I'm using NHiberante and Active Record for the data access layer. There were no problems with regard to their usage, but there are things that I don't like in the interface that they gives you. The problem is that you get an untyped collection. This was sort of OK in 1.0/1.1 but it's a really eye sore for developing in 2.0, where I want everything to be a generic type-safe collection.

Another issue with NHibernate is that the syncing between relationships is not automatic. That is to say, the following code is essentially a no-op:

Blog blog = session.Load(typeof(Blog),1);
blog.Posts.Add(new Post("Briliant Post By Ayende"));
session.Flush();

Since the relationship is maintained on the other side of the connection. (Think about the way it's all laid out in the tables, and you'll understand why.) This is the bare minimum to get it to work:

Post post = new Post("Briliant Post By Ayende")
Blog blog = session.Load(typeof(Blog),1);
post.Blog = blog;
session.Save(post);
session.Flush();

But the above code has a serious shortcoming, it doesn't create the association in the blog, so you would need to re-load the blog from the database to get the change. This is undesirable, naturally, so you can do:

Post post = new Post("Briliant Post By Ayende")
Blog blog = session.Load(typeof(Blog),1);
post.Blog = blog;
blog.Posts.Add(post);
session.Save(post);
session.Flush();

Or create a method AddPost() that will do both operations in one line. This is something that bothers me, I like the natural way of doing blog.Posts.Add(post) to create associations. It's what a developer come to expect. The problem is that you can't add the code to do it to the Add() method on the list since the list is something that NHibernate supplies to you.

On the next installment I'll describe how I'm going to solve this problem.

* I did try, but it's not stable by far yet.

More posts in "NHibernate on .Net 2.0" series:

  1. (01 Oct 2005) Part IV - The Sucess
  2. (01 Oct 2005) Part III
  3. (30 Sep 2005) Part II
  4. (30 Sep 2005) Part I