Reputation: 1033
I need to get the Objects used in a NHibernate Session, that were modified after loading.
The Session Provides the Property IsDirty indicating weather Objects were modified in the Session or not. I Need a Method that Returns me the Objects causing IsDirty to return true.
If you could provide a bit of C# Code to fulfill this Task I would be very greatful.
Upvotes: 10
Views: 5888
Reputation: 1450
Based on the comments of JBL my code to find all "dirty" objects
var dirtyObjects = new List<object>();
var sessionImpl = hsession.GetSessionImplementation();
foreach (NHibernate.Engine.EntityEntry entityEntry in sessionImpl.PersistenceContext.EntityEntries.Values)
{
var loadedState = entityEntry.LoadedState;
var o = sessionImpl.PersistenceContext.GetEntity(entityEntry.EntityKey);
var currentState = entityEntry.Persister.GetPropertyValues(o, sessionImpl.EntityMode);
if (entityEntry.Persister.FindDirty(currentState, loadedState, o, sessionImpl) != null)
{
dirtyObjects.Add(entityEntry);
}
}
Upvotes: 6
Reputation: 1908
Were the objects evicted from the session after loading?
If not that's a very awkward situation, because you don't know if the sql was pushed or not by nhibernate.
Without last update fields, which would be the simplest way to detect dirty state, why don't you load the objects fresh and check for changes through something simple like serialization.
This is as simple as the following:
var staleDirtyObjects = new List<Object>();
foreach(var staleObject in staleObjects)
{
var freshObject = Session.Get<Object>(staleObject.RecId);
var staleObjectJson = JsonConvert.SerializeObject(staleObject);
var freshObjectJson = JsonConvert.SerializeObject(freshObject);
if (!staleObjectJson.Equals(freshObjectJson)) {
staleDirtyObjects.add(staleObject);
}
}
Upvotes: 0