Skip to content

NHibernate.DataAnnotations

ranzlee edited this page Apr 9, 2013 · 8 revisions

Target Framework = 4.0, 4.5

NHibernate = 3.3.3.4000

IMPORTANT: I strongly suggest that you always use a transaction in your unit of work (ISession). The validator will flush the NHibernate ISession to perform validation, so you should be prepared to rollback changes if the session is not valid. This design choice was based on the requirement to keep the session usable from within IValidatableObject.Validate(). If the NHibernate flush was allowed to trigger validation, recursion leading to a stack overflow could result. It seems a little off to allow changes to be (tentatively) persisted before validation, but this actually works quite well. The only concern is whether to commit or rollback changes based on the validation state of the model.

//add the session interceptor to any session you want to plugin to data annotations validation
var session = _sessionFactory.OpenSession(new ValidationInterceptor());

//access the validator at any time via the ISession extension method
var validator = session.GetValidator();

//the validator's simple API
/// <summary>
/// Runs validation on all modified entities in the session.  
/// Commits the transaction if there are no validation errors, otherwise rollsback.
/// </summary>
/// <param name="transaction">The ITransaction object</param>
/// <param name="throwException">True to throw a ValidationException if errors exist</param>
void Eval(ITransaction transaction, bool throwException = true);

/// <summary>
/// Runs validation on all modified entities in the session.
/// </summary>
/// <returns>True, if no errors</returns>
bool IsValid();

/// <summary>
/// Get a string of the concatenated error messages.
/// </summary>
/// <returns>string</returns>
string GetValidationErrorString();

/// <summary>
/// Throw a ValidationException with a message of the validation error string.
/// </summary>
void ThrowValidationException();

/// <summary>
/// Runs validation on all modified entities in the session.
/// </summary>
/// <returns>Dictionary of entities with validation errors</returns>
IDictionary<object, ReadOnlyCollection<ValidationResult>> GetValidationResults();

/// <summary>
/// Runs validation on all modified entities in the session.
/// </summary>
/// <param name="o">The entity to inspect</param>
/// <returns>validation errors</returns>
ReadOnlyCollection<ValidationResult> GetValidationResults(object o);