Is there a way to disable Active Record validation for an nhibernate session / active record scope?
I have a scenario whereby we are performing deletion of a large number of items - and in some cases customers have data in their database that will not pass validation (it was captured prior to new validation rules being introduced, or due to manual manipulation of the database etc.)
When deleting, due the way the database is constructed, some validation checks on existing entities occur, and fail with an exception - preventing the deletion of those entities.
For the deletion scenario we would like to disable all validation from occurring associated with the transaction/session/scope the entities are being deleted within, is this possible?
Update 23/01/2011
Implemented a simple validation active record base class for disabling validation:
public class DisabledValidationProvider : IValidationProvider
{
public bool IsValid()
{
return true;
}
public bool IsValid(RunWhen runWhen)
{
return true;
}
public string[] ValidationErrorMessages
{
get { return null; }
}
public IDictionary PropertiesValidationErrorMessages
{
get { return null; }
}
}
public class DisableValidationScope : IDisposable
{
public DisableValidationScope()
{
Local.Data["DisableValidationScope"] = true;
}
public static bool IsValidationDisabled
{
get { return Local.Data["DisableValidationScope"] != null; }
}
public void Dispose()
{
Local.Data["DisableValidationScope"] = null;
}
}
public abstract class ScopeAwareValidationBase : ActiveRecordHooksValidationBase
{
static readonly IValidationProvider DisabledProvider = new DisabledValidationProvider();
protected override IValidationProvider ActualValidator
{
get
{
if (DisableValidationScope.IsValidationDisabled)
{
return DisabledProvider;
}
return base.ActualValidator;
}
}
}
My ActiveRecord models inherit from ScopeAwareValidationBase and then I can just emplot a using statement around my transaction code, works a treat.
using (new DisableValidationScope())
{
// do transactional thing...
}
I'd look into overriding the
ActualValidator
property, there you could either:To disable validation, you'd return a dummy IValidationProvider that always returned true to IsValid(), etc.