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 conclusiv开发者_运维技巧e answer.
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
If you need to do more complex operations with the collection, you are probably going to need the collection persister, which you can actually get with the following extension method (essentially, you need to work around the visibility by of the AbstractCollectionEvent.GetLoadedCollectionPersister
method):
public static class CollectionEventExtensions
{
private class Helper : AbstractCollectionEvent
{
public Helper(ICollectionPersister collectionPersister, IPersistentCollection collection, IEventSource source, object affectedOwner, object affectedOwnerId)
: base(collectionPersister, collection, source, affectedOwner, affectedOwnerId)
{
}
public static ICollectionPersister GetCollectionPersister(AbstractCollectionEvent collectionEvent)
{
return GetLoadedCollectionPersister(collectionEvent.Collection, collectionEvent.Session);
}
}
public static ICollectionPersister GetCollectionPersister(this AbstractCollectionEvent collectionEvent)
{
return Helper.GetCollectionPersister(collectionEvent);
}
}
Hope it helps!
Best Regards,
Oliver Hanappi
精彩评论