我正在尝试在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]
“应用过滤器”和“已配置”过滤器之间缺少什么,可用于会话?
答案 0 :(得分:5)
仅为类添加过滤器是不够的:您还必须定义它。这归结为添加
<filter-def name="Foo_Nondeleted"></filter-def>
到.hbm.xml文件。请注意,这里有一个问题:虽然教程在课程之前显示它,但它必须放在XML中,或者你会得到XmlSchemaValidationException
。
还需要进行另一项小改动:即使您设置了query.substitutions
来映射false
到0
,也不会将其应用于过滤条件,所以你必须将过滤器更改为
<filter name="Foo_Nondeleted" condition="Deleted = 0" />