This is a mirror of official site: http://jasper-net.blogspot.com/

NHibernate and default constructors

| Tuesday, March 22, 2011
One of the first things you learn about NHibernate is that in order for it to be able construct your instances and take advantage of lazy loading every persistent class must have  the default, parameterless constructor. This leads to having entities looking like this (standard blog with posts and comments example).

public class Post
{
    private readonly IList<Comment> comments = new List<Comment>();
    private Blog blog;
 
    [Obsolete("For NHibernate")]
    protected Post()
    {
       
    }
 
    public Post(string title, string body, Blog blog)
    {
        Blog = blog;
        Title = title;
        Body = body;
        Published = DateTimeOffset.Now;
    }
 
    public virtual int Id { get; private set; }
    public virtual DateTimeOffset Published { get; private set; }
 
    public virtual string Title { get; set; }
    public virtual string Body { get; set; }
 
 
    public virtual IEnumerable<Comment> Comments
    {
        get { return comments; }
    }
 
    public virtual Blog Blog
    {
        get { return blog; }

Notice the first constructor. It doesn’t do anything. As the obsolete message (which is out there to get compilation warning in case some developer accidently calls this constructor in their code) points out – this constructor is there only so that NHibernate can do its magic. Some people do put there initialization logic for collections, (especially when you use automatic properties) but I use fields and initialize them inline. In that case the constructor is pretty much useless. I started thinking why is it even there and that perhaps it doesn’t really belong to the class. But let’s start at the beginning.

What is a constructor
As basic as the question may seem, it is useful to remind ourselves why we need constructors at all. The best book about C# and .NET defines them as follows:

Constructors are special methods that allow an instance of a type to be initialized to a good state.

Notice two important things about this definition. First, it doesn’t say that constructor creates the instance or that constructors are the only way to create the instance. Second, constructors initialize newly created object to their initial state so that anything that uses the object afterwards deals with fully constructed, valid object.

Constructors and persistence
The above definition very well applies to the other constructor we have on the Post class. That constructor initializes the Post to a valid state. In this case valid means the following.
  • Post is part of a blog – we can’t have a post that lives on its own. Our posts need to be part of a blog and we make this requirement explicit by requiring a Blog instance to be provided when constructing Post.

Read more: Krzysztof Kozmic

Posted via email from Jasper-net

0 comments: