viky
viky

Reputation: 21

NHibernate and NHibernate Validation

Is it possible to validate domain model with Nhibernate validation framework in PreTranctionCommint event? If possible how we can write this event ?

Upvotes: 2

Views: 2267

Answers (3)

Xiaolong Liu
Xiaolong Liu

Reputation: 1

how about this?

using(transaction...)
{
    validationA();
    validationB();
    session.saveOrUpdate();(do some transaction)
}

Upvotes: 0

Dmitry
Dmitry

Reputation: 17350

Is it possible to validate domain model with Nhibernate validation framework... ?

If you really have a domain model then it does not need validation framework. In other words the objects encapsulate behavior and protect their internal invariants without relying on external magic-validation framework. Domain objects never get into 'invalid' state in the first place. If they are long-lived then they should also be 'always persistable'. The validity of your domain objects should not rely on the event that may or may not be fired by data access library. You can also find it helpful to not think about VALIDATION because it is overgeneralized and context dependent but instead think about business object INVARIANTS. You don't need thirdparty framework to properly enforce invariants in your objects. It is really not hard to implement it without coupling your domain classes to validation framework.

But if you rephrase your question to:

Is it possible to validate anemic domain model with Nhibernate validation framework... ?

Then the answer would be: Yes, go for it, its awesome! But keep in mind that as complexity grows you would want to enforce more complex domain rules involving multiple object fields, separate domain services etc. You will either get more and more coupled to validation framework by writing 'custom validators' or just give up on it and end up with some rules implemented by framework and other spread all over the code base. It might be worth looking at this answer and DDD in general.

Upvotes: 4

Cole W
Cole W

Reputation: 15303

Excerpt below taken from http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx

NHibernate event-based validation

NHibernate Validator has two built-in NHibernate event listeners. Whenever a PreInsertEvent or PreUpdateEvent occurs, the listeners will verify all constraints of the entity instance and throw an exception if any of them are violated. Basically, objects will be checked before any insert and before any update triggered by NHibernate. This includes cascading changes! This is the most convenient and easiest way to activate the validation process. If a constraint is violated, the event will raise a runtime InvalidStateException which contains an array of InvalidValues describing each failure.

Upvotes: 2

Related Questions