21

It seems I can't find the correct syntax to define a nhibernate filter using fluent Nhibernate.

I'm trying to follow this ayende's blogpost:

http://ayende.com/Blog/archive/2006/12/26/LocalizingNHibernateContextualParameters.aspx

I defined the formula on my property with .FormulaIs() method but can't find on google how to translate this definition to fluent nhibernate:

 < filter-def name='CultureFilter'>
   < filter-param name='CultureId' type='System.Int32'/>
 < /filter-def> 
Drevak
  • 867
  • 3
  • 12
  • 26

3 Answers3

61

If you build Fluent from source, there is now support for filters. You use them like this:

First create a class inheriting from FluentNHibernate.Mapping.FilterDefinition:

using FluentNHibernate.Mapping;

namespace PonyApp.FluentFilters
{
    public class PonyConditionFilter : FilterDefinition
    {
        public PonyConditionFilter()
        {
            WithName("PonyConditionFilter")
                .AddParameter("condition",NHibernate.NHibernateUtil.String);
        }
    }
}

In your ClassMap for your class, use the ApplyFilter method:

namespace PonyApp.Entities.Mappings
{
    public class PonyMap : ClassMap<Pony>
    {
        public PonyMap()
        {
            Id(x => x.Id);
            Map(x => x.PonyName);
            Map(x => x.PonyColor);
            Map(x => x.PonyCondition);
            ApplyFilter<PonyConditionFilter>("PonyCondition = :condition");
        }
    }
}

Then add the filter to your fluent config:

Fluently.Configure()
    .Mappings(m => m.FluentMappings.Add(typeof(PonyConditionFilter)))
    //blah blah bunches of other important stuff left out
    .BuildSessionFactory();

Then you can turn it on and off just as you would with vanilla NHibernate:

session.EnableFilter("PonyConditionFilter").SetParameter("condition","Wonderful");
snicker
  • 6,080
  • 6
  • 43
  • 49
  • 2013 - this is available now in fluentNHibernate without building from sources. – Roopesh Shenoy Aug 26 '13 at 08:50
  • 1
    Your comment helped me a lot. Thank you. By the way, the stept to add the filter to your fluent config is not necessary if there is already a line like: .Mappings(m => m.FluentMappings.AddFromAssemblyOf()) because Fluent NHibernate will "detect" it. – diegosasw Dec 07 '14 at 23:48
9

In case anyone's still watching this, I've just submitted a patch on Google code for Fluent NHibernate to support filters. You can see it in use in snicker's answer above.

David M
  • 71,481
  • 13
  • 158
  • 186
6

This recent post in the Fluent NHibernate discussion leads me to believe that filters are not yet supported by the Fluent API.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117