NHibernate: creating a criterion that applies to all queries in a table

Using Castle ActiveRecord / NHibernate: is there a way to force ICriterion for all queries in a table?

For example, a lot of my tables have a "UserId" column. Perhaps I want me to always select rows for the logged in user. I can easily create an ICriterion object, but I have to provide it for different methods: FindAll (), FindFirst (), FindLast (), etc.

Is there a way to force a WHERE clause for all queries against ActiveRecord Castle?

+2


source to share


2 answers


I finally found a great solution (using filters). Since Castle AR doesn't have any built-in API for mapping to NHibernate filters, this part was almost undocumented. So that's it.

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

First, create an ActiveRecord "News".

Use the following code before initializing 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! News inquiries, for example. FindAll (), DeleteAll (), FindOne (), Exists (), etc. Will never touch records for over a year.

+3


source


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



+1


source







All Articles