views:

25

answers:

1

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 wich does not implements IEnumerable. There is the Entries method that returns an IEnumerable, but it requires an ICollectionPersister wich 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.

Thanks in advance

+2  A: 

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

jfneis
Works great! The only thing to notice is that cast to IList. Using a collection mapped as Set instead of Bag, the interface is ICollection, so we should use IEnumerable instead. Thanks!
Pedro
Good point. Changed my answer to IEnumerable.
jfneis