Sam
Sam

Reputation: 14586

NHibernate Envers: Auditing entity based on property value

I have a very specific need for auditing.

Consider the following class (I changed the name of my classes and trimmed unnecessary code for the sake of simplicity)

[Audited]
public class Client
{
  [NotAudited]
  public virtual IList<Order> Orders {get; set;}
}

The Client entity should only be audited when the Orders property is NOT empty.

Is that at all possible ? If so, how I would I do it ?

Upvotes: 3

Views: 657

Answers (1)

Roger
Roger

Reputation: 1950

If you want to turn off auditing in runtime based on some state, you can make your own custom subclass of AuditEventListenerand pass an instance of that type into IntegrateWithEnvers method.

In your subclass, you can override OnPostDelete, OnPostInsert, OnPostRecreateCollection, OnPostUpdate, OnPreRemoveCollection and OnPreUpdateCollection. In your case, you should probably check evt.Entity and evt.AffectedOwnerOrNull. If you want to audit, simply call base method, if you don't want to audit do nothing in your implementation.

Note however that you should probably just doing this if you just use Envers for simple logging. If you use it to recreate historical instances, "removing" auditing for some historical events may cause problems when loading historical instances. If that's the case for you it's only safe to do this if an entity either has or hasn't got Orders for all its lifetime.

Upvotes: 3

Related Questions