среда, 6 июля 2011 г.

Entity change-tracking with NHibernate

Hi,

here is a tip on entity change-tracking with NHibernate. NHibernate session tracks all of the objects associated with it, thus it's possible not only to determine if entity has been changed, but also if particular property has been changed as well as to get its old value. The following snippet demonstrates this functionality:

public static bool PropertyIsDirty(this ISession session, object entity, string propertyName)
{
var className = NHibernateProxyHelper.GuessClass(entity).FullName;
var sessionImpl = session.GetSessionImplementation();
var persister = sessionImpl.Factory.GetEntityPersister(className);
var oldEntry = sessionImpl.PersistenceContext.GetEntry(sessionImpl.PersistenceContext.Unproxy(entity));
var oldState = oldEntry.LoadedState;
var currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode);
var dirtyProperties = persister.FindDirty(currentState, oldState, entity, sessionImpl);
var index = Array.IndexOf(persister.PropertyNames, propertyName);
var isDirty = dirtyProperties != null && Array.IndexOf(dirtyProperties, index) != -1;

return isDirty;
}
public static object GetOriginalEntityPropertyValue(this ISession session, object entity, string propertyName)
{
var className = NHibernateProxyHelper.GuessClass(entity).FullName;
var sessionImpl = session.GetSessionImplementation();
var persister = sessionImpl.Factory.GetEntityPersister(className);
var oldEntry = sessionImpl.PersistenceContext.GetEntry(sessionImpl.PersistenceContext.Unproxy(entity));
var oldState = oldEntry.LoadedState;
var currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode);
var dirtyProperties = persister.FindDirty(currentState, oldState, entity, sessionImpl);
var index = Array.IndexOf(persister.PropertyNames, propertyName);
var isDirty = (dirtyProperties != null) ? (Array.IndexOf(dirtyProperties, index) != -1) : false;

return isDirty ? oldState[index] : currentState[index];
}

Комментариев нет:

Отправить комментарий