代码之家  ›  专栏  ›  技术社区  ›  Pedro

遍历IPersistentCollection项

  •  1
  • Pedro  · 技术社区  · 15 年前

    OnPostUpdateCollection(PostCollectionUpdateEvent @event)

    我想遍历 @event.Collection 元素。

    IPersistenCollection 它不能实现 IEnumerable . 这就是 Entries I可数 ,但它需要 ICollectionPersister 我不知道在哪能买到。

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

    2 回复  |  直到 5 年前
        1
  •  5
  •   jfneis    15 年前

    佩德罗,

    /// <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
        }
    }
    

        2
  •  2
  •   Oliver Hanappi    15 年前

    如果需要对集合执行更复杂的操作,则可能需要集合持久器,实际上可以通过以下扩展方法获得该持久器(本质上,您需要通过 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);
        }
    }
    

    希望有帮助!

    致以最诚挚的问候,

    推荐文章