2010-08-12 179 views
1

我正在聽的審計事件NHibernate的,專門OnPostUpdateCollection(PostCollectionUpdateEvent @event)迭代通過IPersistentCollection項目

我想通過@event.Collection元素進行迭代。

@ event.Collection是一個IPersistenCollection,它不會執行IEnumerable。有Entries方法返回IEnumerable,但它需要一個ICollectionPersister至極,我不知道我可以在哪裏得到一個。

這裏的問題已經在這裏問:http://osdir.com/ml/nhusers/2010-02/msg00472.html,但沒有確鑿的答案。

在此先感謝

回答

5

佩德羅,

搜索NHibernate的代碼,我可以找到關於IPersistentCollection的GetValue方法(@ 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(); 

就這樣,我們就可以得出結論,你可以將你的集合轉換爲IEnumerable,事情會正常工作。

我已經建立了一個小樣本映射一個袋子,事情就這樣在這裏:

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

希望這有助於!

菲利佩

+1

偉大的作品!唯一要注意的是投給IList。使用映射爲Set而不是Bag的集合,接口是ICollection,所以我們應該使用IEnumerable。謝謝! – Pedro 2010-08-12 14:22:31

+0

好點。將我的答案更改爲IEnumerable。 – jfneis 2010-08-12 15:17:46

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

希望它有幫助!

最好的問候,
奧利弗Hanappi

+0

非常好,希望我可以兩次upvote – Pedro 2011-03-24 13:32:16