NHibernate: Creating a criteria which applies for all queries on a table

百般思念 提交于 2019-12-06 13:32:45

I finally found a great solution (using filters). Since Castle AR does not have any native API for mapping to NHibernate filters, this part was pretty much undocumented. So here goes.

This example filter, will make sure you will never get news more than a year old, no matter what kind of query you use on the ActiveRecord. You can probably think of more practical applications for this.

First, create an ActiveRecord "News".

Use the following code before you initialize ActiveRecordStarter.

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

Then, add the missing function and class:

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));
    }
}

And voila! Queries on News, e.g. FindAll(), DeleteAll(), FindOne(), Exists(), etc. will never touch entries more than a year old.

The closest thing would be using filters. See http://ayende.com/Blog/archive/2009/05/04/nhibernate-filters.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!