Newbie
Newbie

Reputation: 7249

How to add Filter definitions with Nhibernate 3.2 mapping by code?

The ModelInspector doesn't seem to provide the means to define Filter definitions . Any ideas/Workarounds?

I need to generate the following with mappings by code:

<filter-def name="filterName" use-many-to-one="false">
  <filter-param name="filterParamName" type="Int32"/>
</filter-def>

Upvotes: 6

Views: 2870

Answers (2)

Simon M
Simon M

Reputation: 61

FYI,

It is important to note that the call to AddFilterDefinition is before AddMapping, otherwise you will get anArgumentException("An item with the same key has already been added")!

Upvotes: 6

Robert Wilczynski
Robert Wilczynski

Reputation: 921

I was able to achieve that using NHibernate.Cfg.Configuration:

var cfg = new Configuration();

var filterDef = new FilterDefinition(
    "filterName",
    null, // or your default condition
    new Dictionary<string, IType> { { "filterParamName", NHibernateUtil.Int32 } },
    false);
cfg.AddFilterDefinition(filterDef);

// cfg.AddMapping(...)
// cfg.DataBaseIntegration(...)

var sessionFactory = cfg.BuildSessionFactory();

then define the filter in entity mapping:

public class EntityMap : ClassMapping<Entity>
{
    public EntityMap()
    {
        Table("Entity");
        Filter("filterName", m => m.Condition("FilteredField = :filterParamName"));
        // remaining mapping
    }
}

and then use it as follows:

using(var session = sessionFactory.OpenSession())
{
    var filterValue = 123;
    session
        .EnableFilter("filterName")
        .SetParameter("filterParamName", filterValue);
}

I hope you;ll find this useful.

Upvotes: 10

Related Questions