views:

143

answers:

2

I'm using NHibernate as my ORM. I have a situation where I have some stuff wrapped in an ITransaction. I am listening to the SaveUpdate event in NHibernate and then doing my entity validation in that SaveUpdate handler.

For one of my entities, I want to validate that the value of a certain property hasn't changed. So I figured that I would load up the value of the existing object from the database and compare it with the new value. The problem is that I called ITransaction.Commit() to save my entity object and the transaction hasn't actually been committed at the time that validation occurs, so I can't load the existing object from the database because the transaction has it locked.

So I guess I have a few different questions here: - Is the SaveUpdate event the correct place to do validation? - Is there another way I can do this so that I can do the validation that I need to do (getting the existing value from the database and comparing)?

I'm sure someone else out there has run into a similar situation...... hopefully!

A: 

Validation has nothing to do with persistence, so saveupdate is not the right place. The correct place of validation depends on: what you want to validate, your programming style, the UI framework you use to show the validation messages, etc. Personally, I prefer to put the validation on the place where things are changed, so I would put it in the change method that sets the property. I don't understand why you want to load the entity in the previous state, because that state is already loaded when you load it for the first time.

Paco
I disagree. I ultimately want to validate my entities before the save, so I think it does have something to do with persistence. Putting validation on properties works for simple cases, but sometimes the validation rules involve more than just a single entity (e.g. a bank account can only have one primary account holder).
Jon Kruger
That not a reason to not use methods to change things in your entities. The aggregate root should be responsible for validating it's child entities.
Paco
But what about when I save a child entity of an aggregate root?
Jon Kruger
You shouldn't save them separate from the root, but with the root
Paco
A: 

If you want to see an example of how to do validation, I suggest checking out ScottGu's NerdDinner. Although he's using Linq to SQL for his ORM, it's very easy to adapt it to NHibernate.

I recently used a validation system similar to the NerdDinner one in an ASP.NET MVC + NHibernate project with great success.

cdmckay