3

I try to find out how to identify that parent object is Dirty when one of the objects in the child collection was changed by using the features of the NHibernate context.

I mean for the following case:

public class Parent
{
   public IList<Child> Childs { get; set; }
}

public class Child
{
   public String Name {get; set; }
}

...

var parent = session.Get<Parent>(1);
parent.Childs[0].Name = "new name";
// here <code>session.IsEntityDirty(parent)</code> should return true

I know about extensions to the ISession like here http://nhibernate.info/doc/howto/various/finding-dirty-properties-in-nhibernate.html and here for collection NHibernate: Find dirty collections. But neither first (it tracks just properties), nor second (it tracks just operations add/delete on collection object) work.

I want also to mention that I prefer to use plain POCOs instead of STEs.

I would be very appreciate for a solution.

Community
  • 1
  • 1
dmitrygrig
  • 61
  • 6

1 Answers1

0

It does not look if NHibernate is checking if the the object graph is dirty but on the entity itself. So it ignores collections and other references.

If you follow the code

EntityEntry oldEntry = persistenceContext.GetEntry(entity);
Object[] oldState = oldEntry.LoadedState;

The oldState only includes the original values of the entity, but includes the current values of the collection. So my guess is that NHibernate does not take that into account but does another loop somewhere to loop through those entities in the list and check them separately.

The way I would do it is by looping through the properties of the entity and check that with session.IsDirtyProperty skipping over collections and other entity type properties, but then looping through collections and for each entity in the collection checking against that entity's properties.

Remember that your session will need to stay open and not flushed for this to work before checking, if the entity gets detached from the session there won't be a way to use NHibernate to check if it is dirty.

It is also not recommended to keep a session open for a long time, you should use it and dispose it when you done.

adriaanp
  • 2,064
  • 2
  • 22
  • 40
  • Yes, I know that old stores the same values for collections, that's why this extension doesn't work. Of course, it is possible to loop over all properties, but I found this solution a little bit cumbersome. Also then I should take into account that the child entities have a reference to a parent entity (as a property). – dmitrygrig Aug 22 '13 at 10:15