Friday, February 16, 2007

nhibernate - a complex beast

I am beginning to discover that nHibernate is a far more complex beast than I realised. Over the last couple of days I've spent some more time reading the documentation (out of necessity rather than pure interest) and it is capable of some amazing things, however this flexiblity comes at the cost of complexity (as is often the case).

Here's an example of a trap for young players that caught me the other night. I have two entities A & B that map two two underlying tables tableA and tableB. The primary key of tableA is a foreign key in tableB. tableA contains a property Rating1Count which is the count of a column in tableB. I had code similar to the following:

ISession session = NHibernateHttpModule.CurrentSession;
ITransaction transaction = session.BeginTransaction();
    log.Debug("Saving new B");

    log.Debug("saved new B");
    ICriteria crit = session.CreateCriteria(typeof(A));
    crit.Add( Expression.Eq("AId", a.AId) );
    log.Debug("Executing query");
    IList As = crit.List();
    if (As.Count == 1)
        a = As[0] as A;
        log.Debug(string.Format("Count of 1s in tableB {0}", a.Rating1Count));

After testing this I found that even though my changes were being persisted to tableB (verified by querying mysql directly) they weren't reflected in my tableA object.

Then it dawned on me, at what point does nhibernate write the changes to the database? I moved the transaction.Commit line up to be directly below the call to SaveOrUpdate and lowe and behold it works!

In hindsight it's obvious, but it had me scratching my head for a while (and it was late - at least that's my story and I'm sticking to it!).

Labels: ,


Post a Comment

<< Home