Search code examples
nhibernateaudit

Iterate through IPersistentCollection items


I am listening to audit events in NHibernate, specifically to OnPostUpdateCollection(PostCollectionUpdateEvent @event)

I want to iterate through the @event.Collection elements.

The @event.Collection is an IPersistenCollection which does not implements IEnumerable. There is the Entries method that returns an IEnumerable, but it requires an ICollectionPersister which I have no idea where I can get one.

The questions is already asked here: http://osdir.com/ml/nhusers/2010-02/msg00472.html, but there was no conclusive answer.


Solution

  • Pedro,

    Searching NHibernate code I could found the following doc about GetValue method of IPersistentCollection (@event.Collection):

    /// <summary>
    /// Return the user-visible collection (or array) instance
    /// </summary>
    /// <returns>
    /// By default, the NHibernate wrapper is an acceptable collection for
    /// the end user code to work with because it is interface compatible.
    /// An NHibernate PersistentList is an IList, an NHibernate PersistentMap is an IDictionary
    /// and those are the types user code is expecting.
    /// </returns>
    object GetValue();
    

    With that, we can conclude that you can cast your collection to an IEnumerable and things will work fine.

    I've built a little sample mapping a bag and things got like that over here:

    public void OnPostUpdateCollection(PostCollectionUpdateEvent @event)
    {
        foreach (var item in (IEnumerable)@event.Collection.GetValue())
        {
            // DO WTVR U NEED
        }
    }
    

    Hope this helps!

    Filipe