2

I'd like all queries that query a certain type, to include a where statement by default.

More exactly, I have an interface IIsTenantSpecific, with a property TenantId - so the entities belong to a single tenant.

When I query a type implenting this interface, then NHIberante should always add a WHERE clause, filtering the TenantId.

Is there a mechanism (like interceptor, or event listener) in NHibernate that allows this easily?

Bertvan
  • 4,943
  • 5
  • 40
  • 61

1 Answers1

4

I would say, that this scenario could be easily covered by built in feature:

18.1. NHibernate filters

Similar Q & A

A cite from the doc:

NHibernate adds the ability to pre-define filter criteria and attach those filters at both a class and a collection level. A filter criteria is the ability to define a restriction clause very similiar to the existing "where" attribute available on the class and various collection elements. Except these filter conditions can be parameterized. The application can then make the decision at runtime whether given filters should be enabled and what their parameter values should be. Filters can be used like database views, but parameterized inside the application.

In order to use filters, they must first be defined and then attached to the appropriate mapping elements. To define a filter, use the <filter-def/> element within a <hibernate-mapping/> element:

<filter-def name="myFilter">
    <filter-param name="myFilterParam" type="String"/>
</filter-def>

Then, this filter can be attached to a class:

<class name="MyClass" ...>
    ...
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</class>

or, to a collection:

<set ...>
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</set>

So, once we define a filter, and apply it on our collections - we can later easily at any time turn that filter on on a whole session:

session.EnableFilter("myFilter").SetParameter("myFilterParam", "some-value");

And from that moment, each collection is filtered with passed "some-value" over selected column

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335