2011-09-28 103 views
1

我想在NHibernate中使用一個全局過濾器,並且據我所知,我正在做所有的教程都做了什麼,但我得到一個異常。爲什麼NHibernate會說我的過濾器沒有配置?

我的.hbm.xml文件包含以下內容:

... 
<class name="NHibernateSandbox.Foo, NHibernateSandbox" table="Foo"> 
    ... 
    <property column="Content" type="String" name="Content" not-null="true" length="100" /> 
    <property column="Deleted" type="Boolean" name="Deleted" not-null="true" /> 
    <filter name="Foo_Nondeleted" condition="Deleted = false" /> 
</class> 

然後,我有一個簡單的測試類:

Configuration cfg = new Configuration(); 
cfg.Configure(); 

using (ISessionFactory sf = cfg.BuildSessionFactory()) { 
    using (ISession session = sf.OpenSession()) { 
     session.EnableFilter("Foo_Nondeleted"); 
     IQuery query = session.CreateQuery("FROM NHibernateSandbox.Foo"); 
     foreach (Foo foo in query.List<Foo>()) { 
      Console.WriteLine(foo.Content); 
     } 
    } 
} 

如果我刪除EnableFilter線它按預期工作:既刪除,未打印的行被打印。然而,隨着EnableFilter線,我得到一個NHibernateException

No such filter configured [Foo_Nondeleted] 
    at NHibernate.Impl.SessionFactoryImpl.GetFilterDefinition(String filterName) 
    at NHibernate.Impl.SessionImpl.EnableFilter(String filterName) 
    at NHibernateSandbox.Program.Main(String[] args) 

如果我配置log4net的是冗長的,然後我看到

INFO NHibernate.Cfg.HbmBinder - Mapping class: NHibernateSandbox.Foo -> Foo 
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Id -> RID, type: Int32 
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Content -> Content, type: String 
DEBUG NHibernate.Cfg.HbmBinder - Mapped property: Deleted -> Deleted, type: Boolean 
DEBUG NHibernate.Cfg.HbmBinder - Applying filter [Foo_Nondeleted] as [Deleted = false] 

什麼是它的梯級缺失「應用過濾器」和被「配置的過濾器「並提供給會議?

回答

5

僅向類中添加過濾器是不夠的:您還必須定義它。這歸結爲添加到.hbm.xml文件

<filter-def name="Foo_Nondeleted"></filter-def> 

。請注意,這裏有一個問題:儘管教程在課程之前顯示,但必須放在XML之後,否則您將獲得XmlSchemaValidationException

有需要被太立另一個小的變化:即使你可能有query.substitutions設置爲映射到false0,它不適用於過濾條件,那麼你就必須更換過濾器,以

<filter name="Foo_Nondeleted" condition="Deleted = 0" /> 
相關問題