I've just read Hammett's ActiveRecord SessionScope blog post [1] and I thought it could be useful to someone if a share my mistake :)
 
Before being aware of the default behavior described on the post, I had been misusing the (ActiveRecordValidationBase.)IsValid() method

Suppose the name passed to the method below is null (and Office.Name property has the ValidateNotEmpty() attribute)

public void Update(int officeId, string name, int langId)
{
 Office office = Office.Find(officeId);

 office.Name = name;
 office.Language = Language.Find(langId);
 
 if ( office.IsValid() )
 {

  officeService.Update( office );

  // User Response - Ok
 }
 else
 {
  // User Response - Error
 }
 ...
}

Using one session per request, with the the default behavior and the code above,
will result in an invalid name (null) persisted to database. :(


I wanted the default flush behavior mostly time, so I changed the code to:

public void Update(int officeId, string name, int langId)
{
 Office office = Office.Find(officeId);

 office.Name = name;
 office.Language = Language.Find(langId);

 try
 {
  officeService.Update( office );

  // User Response - Ok
 }
 catch(ValidationException ex)
 {
  // User Response - Error
 }
 ...
}

The code above works because NHibernate call NHibernate.IValidatable.Validate() before flush the entity and ActiveRecordValidationBase helpfully implements the NHibernate.IValidatable interface.
Simplifying, if ActiveRecord validation fails an ValidationException is thrown aborting NHibernate flushing process, and the entity with invalid changes is not persisted.

[1] http://hammett.castleproject.org/?p=18

HTH,
Jordi
_______________________________________________
CastleProject-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/castleproject-users

Reply via email to