It sounds like you could use filters to do this.
First, you need to define the filter types
public class SpecificCategoryFilter : FilterDefinition
{
public SpecificCategoryFilter()
{
WithName("SpecificCategory").WithCondition("Category = 'A constant expression'");
}
}
public class SpecificLanguageFilter : FilterDefinition
{
public SpecificLanguageFilter()
{
WithName("SpecificLanguage").WithCondition("Language = 'A constant expression'");
}
}
EDITED: As per comments, there is no .ApplyFilter<TFilter>()
on References()
, so have updated with what I believe is the way to do it with filters
The filters need to be applied in the fluent mappings
public class Table2Map : ClassMap<Table2>
{
public Table2Map()
{
// Other mappings here...
ApplyFilter<SpecificCategoryFilter>();
ApplyFilter<SpecificLanguageFilter>();
}
}
Finally, when you open a session, you need to enable the filters
using (var session = sessionFactory.OpenSession())
{
session.EnableFilter("SpecificCategory");
session.EnableFilter("SpecificLanguage");
}
If you're using an implementation of ICurrentSessionContext
and the filters should always apply then you can enable the filters in the session returned from the call to ICurrentSessionContext.CurrentSession()
.
Now, when querying Table1
, in order to activate the filters for Table2
, you need to indicate to NHibernate to join to the referenced Table2
; you can do this using
Fetch(t => t.Table2).Eager
JoinQueryOver(t => t.Table2)
(and similar join strategies)
Without indicating to NHibernate to make the join, the reference will be lazily-loaded by default and hence the filters will not be applied in the query. The downside is that Table2
will be eager fetched but I don't know of a way to have the filters applied otherwise. The following query
session.QueryOver<Table1>().Inner.JoinQueryOver(t => t.Table2).List();
results in SQL similar to
SELECT
this_.Id as Id0_1_,
this_.Table2Id as Table3_0_1_,
table2_.Id as Id1_0_,
table2_.Category as Category1_0_,
table2_.Language as Language1_0_
FROM
Table1 this_
inner join
Table2 table2_
on this_.Table2Id=table2_.Id
WHERE
table2_.Category = 'A constant expression'
and table2_.Language = 'A constant expression'
which is akin to the SQL that you have in your question.