Try fast search NHibernate

31 October 2009

Validation through persistence: not synchronized

In this series you saw mostly the configuration of NHibernate.Validator through Loquacious (our configuration based on fluent-interface).

What is the ValidationDef<T> ?

If you are using the Satisfier (validation through lambdas) the ValidationDef become the class whose responsibility is validate a instance of T.

If you need some validation, involving the persistence, and you want do it through NHV, which is the best candidate class where implement the validation ?

Let me show you how much easy is it:

public class BlogPostSofValidation : ValidationDef<BlogPost>
private readonly ISessionFactory factory;

public BlogPostSofValidation(ISessionFactory sessionFactory)
factory = sessionFactory;
ValidateInstance.By((bp, c) => !Exists(bp));

private bool Exists(BlogPost post)
if (ReferenceEquals(post, null))
return true;
using (var session = factory.OpenStatelessSession())
var criteria = session.CreateCriteria(typeof(BlogPost));
criteria.Add(Restrictions.Eq("Title", post.Title));
criteria.Add(Restrictions.Eq("Date", post.Date));
return criteria.UniqueResult() != null;

Here I’m showing only the part involving the persistence but you know… there you can define the validation of any other property as usual.

To register this definition the work to do is very easy:

var veConfig = new FluentConfiguration();
veConfig.Register(new BlogPostSofValidation(sessionFactory))
validatorEngine = new ValidatorEngine();

and that it’s all (the usage is identical of the previous post).

1 comment:

  1. In this post as much as in previous validation correctly applied to new instances. I think in both cases missing check when the instance is not new and therefore it findeth itself and persisted.