2010-08-12 172 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