2009-08-31 52 views
2

使用Castle ActiveRecord/NHibernate:有没有一种方法可以在表上的所有查询上强制使用ICriterion?NHibernate:创建适用于表上所有查询的标准

例如,我的表一个良好的数额有一个“用户ID”列。我可能想要确保我总是为登录用户选择行。我可以很容易地创建一个ICriterion对象,但我不得不提供它用于不同的方法:FindAll(),FindFirst(),FindLast()等。

是否有强制所有查询的WHERE子句的方法Castle ActiveRecord?

回答

3

我终于找到了一个很好的解决方案(使用过滤器)。由于Castle AR没有任何本地API来映射到NHibernate过滤器,所以这部分内容几乎没有记录。所以在这里。

此示例过滤器将确保您永远不会获得超过一年的新闻,无论您在ActiveRecord上使用哪种查询。你可以考虑更实际的应用。

首先,创建一个ActiveRecord的 “新闻”。

初始化ActiveRecordStarter之前使用下面的代码。

ActiveRecordStarter.MappingRegisteredInConfiguration += MappingRegisteredInConfiguration; 
Castle.ActiveRecord.Framework.InterceptorFactory.Create =() => { return new EnableFiltersInterceptor(); }; 

然后,添加缺少的函数和类:

void MappingRegisteredInConfiguration(Castle.ActiveRecord.Framework.ISessionFactoryHolder holder) 
{ 
    var cfg = holder.GetConfiguration(typeof (ActiveRecordBase)); 

    var typeParameters = new Dictionary<string, IType> 
            { 
            {"AsOfDate", NHibernateUtil.DateTime} 
            }; 

    cfg.AddFilterDefinition(new FilterDefinition("Latest", "", typeParameters)); 

    var mappings = cfg.CreateMappings(Dialect.GetDialect(cfg.Properties)); 

    var newsMapping = cfg.GetClassMapping(typeof (News)); 
    newsMapping.AddFilter("Latest", ":AsOfDate <= Date"); 
} 


public class EnableFiltersInterceptor : EmptyInterceptor 
{ 
    public override void SetSession(ISession session) 
    { 
     session.EnableFilter("Latest").SetParameter("AsOfDate", DateTime.Now.AddYears(-1)); 
    } 
} 

瞧!新闻查询,例如的FindAll(),DeleteAll(),FindOne(),是否存在()等,将永远无法触摸满周岁多个条目。

1
+0

这似乎是一个很好的解决方案,但我无法弄清楚它是否有可能在Castle ActiveRecord中使用这些过滤器。 – mbp 2009-09-02 17:57:04

+0

http://groups.google.com/group/castle-project-devel/browse_thread/thread/ce94f492615e0d52/c721a7abb0a1f1a7我不认为这已经实现......您将获得当前的ISession并启用过滤器你自己 – 2009-09-02 19:58:57

+0

IIRC你可以从ActiveRecordMediator.GetSessionFactoryHolder()获取当前的ISession。CreateSession(typeof(ActiveRecordBase)) – 2009-09-02 19:59:38