Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 922
Newbie Avatar asked Oct 27 '11 21:10

Newbie


2 Answers

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.

like image 194
Robert Wilczynski Avatar answered Nov 19 '22 18:11

Robert Wilczynski


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")!

like image 41
Simon M Avatar answered Nov 19 '22 16:11

Simon M