Here is my interceptor, adapt for your own need:
Code:
public class PersistenceInterceptor : NHibernate.EmptyInterceptor
{
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
{
// This method is called when a new entity is saved.
// When updating, this is not called.
bool stateChanged = false;
if (entity is ICreationLogged)
{
bool iCreationLoggedPropertiesChanged = UpdateICreationLoggedProperties(state, propertyNames);
stateChanged = stateChanged || iCreationLoggedPropertiesChanged;
}
if (entity is ILastUpdateLogged)
{
bool iLastUpdateLoggedPropertiesChanged = UpdateILastUpdateLoggedProperties(state, propertyNames);
stateChanged = stateChanged || iLastUpdateLoggedPropertiesChanged;
}
return stateChanged;
}
private bool UpdateICreationLoggedProperties(object[] state, string[] propertyNames)
{
bool stateChanged = false;
for (int i = 0; i < propertyNames.Length; i++)
{
if ("CreateDateTime".Equals(propertyNames[i]))
{
state[i] = DateTime.Now;
stateChanged = true;
}
else if ("CreateUserId".Equals(propertyNames[i]))
{
if (ThreadLocalData.Instance.UserSession != null)
{
state[i] = ThreadLocalData.Instance.UserSession.UserId;
stateChanged = true;
}
}
}
return stateChanged;
}
public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
{
// This method is called when an entity is updated.
bool stateChanged = false;
if (entity is ILastUpdateLogged)
{
stateChanged = UpdateILastUpdateLoggedProperties(currentState, propertyNames);
}
return stateChanged;
}
private bool UpdateILastUpdateLoggedProperties(object[] currentState, string[] propertyNames)
{
bool stateChanged = false;
for (int i = 0; i < propertyNames.Length; i++)
{
if ("LastUpdateUserId".Equals(propertyNames[i]))
{
if (ThreadLocalData.Instance.UserSession != null)
{
int? userId = ThreadLocalData.Instance.UserSession.UserId;
if (!Nullable<int>.Equals(currentState[i], userId))
{
currentState[i] = userId;
stateChanged = true;
}
}
}
else if ("LastUpdateDateTime".Equals(propertyNames[i]))
{
DateTime? dateTime = DateTime.Now;
if (!Nullable<DateTime>.Equals(currentState[i], dateTime))
{
currentState[i] = dateTime;
stateChanged = true;
}
}
}
return stateChanged;
}
}