NHibernate on .Net 2.0Part III

time to read 5 min | 907 words

I managed to build an addon to NHibernate that would allows you to use generic collections in NHibernate. Well, one collection, EntitySet<T>, but it's the principal that matter, and it's very easy to write additional classes to do the same for the other collections if you really wants it.

I used a custom PropertyAccessor, and I'm planning on releasing it tomorrow (once I wrote enough tests). But here is the client code that you'll have to write:

Post post = new Post();
blog.Posts.Add(post);
//Or you could do:
//post.Blog = blog;
//But you don’t have to do both
session.Save(post);

Here is how it looks like to the author of the classes:

public class Blog
{
 ...
 
 EntitySet<Post> _posts;
 
 public ICollection<Post> Posts
 {
  get { return _posts; }
 }
 
 public Blog()
 {
  _posts = new EntitySet<Post>(
   delegate (Post p) { p.Blog = this; },
   delegate (Post p) { p.Blog = null; }
   );
 }
 
 ...
}
public class Post
{
 ...
 
 EntityRef<Blog> _blog;
 
 public Blog Blog
 {
  get { return _blog.Value; }
  set { _blog.Value = value; }
 }
 
 public Post()
 {
  _blog = new EntityRef<Blog>(
   delegate(Blog b) { b.Posts.Add(this); }
   delegate(Blog b) { b.Posts.Remove(this); }
   );
 }
 
 ...
}

This has a lot of goodies in it:

  • The users gets the strongly typed generic collections and properties that they come to expect in .Net 2 (ICollection<Post> Post & Blog Blog, respectively).
  • The author of the class doesn't really have to do something special, just tell the EntitySet & EntityRef how it wants the relationships to act when you add/remove or change/clear the reference.
  • Nothing special that you need to do (beyond giving a special access strategy to the Posts property in the mapping, but I'll add this tomorrow to Active Record, so this would be a piece of cake)

The guide lines for this are going to be:

  • Don't expose a setter for the EntitySet<>. This is genenrally a sound advice anywhere where you're exposing collections to the outside world.
  • Don't expose an EntityRef<> directly, use its Value property inside the property and let it manage the connections for you.
  • The most important guide line is going to be: Have fun, because you just saved a lot of time :-)

 

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