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;
开发者_JAVA技巧 }
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:
- provide a setter, to let your code decide whether to apply validation or not on a per-instance basis, or
- (better) look up some context associated to the current SessionScope that decides whether to apply validation or not.
To disable validation, you'd return a dummy IValidationProvider that always returned true to IsValid(), etc.
精彩评论