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

2

6

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>
Ninanincompoop answered 27/10, 2011 at 21:1 Comment(0)
B
10

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.

Bent answered 11/11, 2011 at 0:24 Comment(0)
L
6

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

Ledger answered 5/4, 2012 at 6:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.