R – How to add additional criteria to the update command using NHibernate

nhibernate

I have situation where a Message table has a primary key (Id) and a foreign key (Site). Any site can create a message record, but only the site that created the record can update it. The problem is that by default it will be updated based upon Id and not Id and Site. I could change the primary key to be a composite/compound id consisting of the id and site OR resort to Native SQL; however, I was wondering if there is a way to add additional Update criteria.

For example, this is what you get by default:

public void MessageUpdate(Message oneMessage)
{
    using(ISession session = SessionFactory.OpenSession())
    using(ITransaction trans = session.BeginTransaction())
    {
        session.Update(oneMessage);
        trans.Commit();
    }
}

So how do I do this in NHibernate without creating a compound id or using Native SQL:

Update MessageTable set MessageStatus = 2 where Id = ? and Site = ?;

Best Answer

You can't do it directly in NHibernate but you could alter your update method to:

public void MessageUpdate(Message oneMessage, string currentSite)
{
    if (oneMessage.Site != currentSite)
    {
        throw new Exception("meaningful error message");
    }
    using(ISession session = SessionFactory.OpenSession())
    using(ITransaction trans = session.BeginTransaction())
    {
        session.Update(oneMessage);
        trans.Commit();
    }
}

Assuming Site is a string and a property of Message. Also, you will want to wrap your update in a try..catch and rollback the transaction if an exception occurs.

Related Topic