1

我正在听 NHibernate 中的审计事件,特别是OnPostUpdateCollection(PostCollectionUpdateEvent @event)

我想遍历@event.Collection元素。

@event.Collection 是IPersistenCollection不实现的IEnumerable。有一种Entries方法返回一个IEnumerable,但它需要一个ICollectionPersister我不知道在哪里可以得到的方法。

这些问题已经在这里提出:http: //osdir.com/ml/nhusers/2010-02/msg00472.html,但没有确凿的答案。

4

2 回答 2

5

佩德罗,

搜索 NHibernate 代码我可以找到以下关于 IPersistentCollection (@event.Collection) 的 GetValue 方法的文档:

/// <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();

有了这个,我们可以得出结论,您可以将您的集合转换为 IEnumerable 并且一切正常。

我已经建立了一个映射包的小样本,这里的事情就是这样:

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

希望这可以帮助!

菲利普

于 2010-08-12T14:12:36.587 回答
2

如果您需要对集合进行更复杂的操作,您可能需要集合持久化器,您实际上可以通过以下扩展方法获得它(本质上,您需要通过该AbstractCollectionEvent.GetLoadedCollectionPersister方法来解决可见性问题):

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);
    }
}

希望能帮助到你!

最好的问候,
奥利弗·哈纳皮

于 2011-03-18T08:21:03.507 回答