NHibernate Step By Step(8)-数据过滤器
2010-08-26 23:56 Clingingboy 阅读(736) 评论(0) 编辑 收藏 举报
1.定义过滤器
<filter-def name="LiveFilter"> <filter-param name="LiveParam" type="boolean"/> </filter-def> <filter-def name="LiveFilter2"> <filter-param name="LiveParam2" type="string"/> </filter-def>
2.在映射文件中使用过滤器
犹如在hql中下查询语句
<class name="TestClass"> <id name="Id" column="id"> <generator class="assigned" /> </id> <property name="Name" type="StringClob" length="100000" /> <property name="Live" type="Boolean" /> <filter name="LiveFilter" condition=":LiveParam = Live"/> <filter name="LiveFilter2"><![CDATA[Name = :LiveParam2]]></filter> </class>
3.在配置文件中获取过滤器
public void FilterDefinitionsLoadedCorrectly() { Configuration cfg = new Configuration(); cfg.AddResource(mappingCfg, this.GetType().Assembly); Assert.AreEqual(cfg.FilterDefinitions.Count, 2); Assert.IsTrue(cfg.FilterDefinitions.ContainsKey("LiveFilter")); FilterDefinition f = cfg.FilterDefinitions["LiveFilter"]; Assert.AreEqual(f.ParameterTypes.Count, 1); BooleanType t = f.ParameterTypes["LiveParam"] as BooleanType; Assert.IsNotNull(t); //ensure that the parameter is the correct type. }
4.启动过滤器
ISession</TT对象中会用到的方法有: class=literal EnableFilter(string filterName), GetEnabledFilter(string filterName), 和 DisableFilter(string filterName). ISession 中默认是不启用过滤器的,必须通过ISession.EnableFilter()方法显式的启用。 该方法返回被启用的IFilter的实例
通过启用EnableFilter方法启用过滤器
public void FiltersLoaded() { Configuration cfg = new Configuration(); cfg.AddResource(mappingCfg, this.GetType().Assembly); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); IFilter filter = session.EnableFilter("LiveFilter"); Assert.AreEqual(filter.FilterDefinition.FilterName, "LiveFilter"); filter.SetParameter("LiveParam", true); filter.Validate(); // make sure that everything is set up right. IFilter filter2 = session.EnableFilter("LiveFilter2"); filter2.SetParameter("LiveParam2", "somename"); filter2.Validate(); }
IFilter接口