views:

71

answers:

1
public MyClass(int someUniqueID)
{
    using(//Session logic)
    {
    var databaseVersionOfMyClass = session.CreateCriteria(/*criteria*/)
     .UniqueResult<MyClass>();

    //Load logic
    }
}

The code sample above is my current direction, although I've reached a point where I need a bit of a sanity check.

With NHibernate(I'm green in this area), is it common or best practice to instantiate an object from a database within the class constructor? The alternative I believe, would be to have a static method that returns the object from the database.

I've also come across a relevent question regarding constructors vs factory methods, however I don't believe this implementation fits the factory methodology.

To add an additional question onto the above, if instantiation within the constructor is the way to go, I've always used some sort of Load() method in the past. Either a specific private method that literally matches properties from the returned db object to the new class, or via a generic reflective method that assumes property names will match up. I'm curious if there is another way to "load" an object that I've missed.

+2  A: 

I do not like this approach. IMHO , it is better to implement some kind of repository which retrieves instances of persisted classes for you. As an alternative, you could also follow the ActiveRecord approach, where you could have a static 'Load' method inside your class, and an instance method 'Save' for instance. (Take a look at Castle ActiveRecord).

But, for me, I prefer the Repository approach.

Frederik Gheysels
I think the Repository patter with the Unit of Work pattern might be what I was needing to come across. I've spent a bit of time in the LINQ world and slowly settling back down into reality here ;) Thanks for the response Frederik.
Alexis Abril