views:

346

answers:

1

My scenario is this: I have a base NHibernate query to run of the form (I've coded it using DetachedCriteria , but describe it here using SQL syntax):

SELECT * FROM Items I INNER JOIN SubItems S on S.FK = I.Key

The user interface to show the results of this join allows the user to specify additional criteria: Say:

I.SomeField = 'UserValue'.

Now, I need the final load command to be:

SELECT * FROM Items I INNER JOIN SubItems S on S.FK = I.Key
WHERE I.SomeField = 'UserValue'

My problem is: I've created a DetachedCriteria with the 'static' aspect of the query (the top join) and the UI creates a DetachedCriteria with the 'dynamic' component of the query. I need to combine the two into a final query that I can execute on the NHibernate session.

DefaultCriteria.Add() takes an ICriterion (which are created using the Expression class, and maybe other classes I don't know of which could be the solution to my problem).

Does anyone know how I might do what I want?

A: 

You can use GetExecutableCriteria to turn a detached criteria into an executable form for a specific session:

var query = DetachedCriteria.For<...>();

using (var session = ...)
using (var transaction = session.BeginTransaction())
{
    query.GetExecutableCriteria(session)
    transaction.Commit();
}

However, I think your design is a little flawed. The UI should be supplementing the criteria, not creating its own. At worst, it should be generating ICriterion that are then added to your criteria prior to execution. At best, you would abstract away filtering capabilities into a layer completely independent of your ORM technology and then apply filters from the UI to your underlying criteria.

HTH,
Kent

Kent Boogaart
Thanks Kent. I came to the same conclusion after posting the question.I've changed my 'UI' (its actually DTO Factory code, not really UI) to generate ICriterion. Good point about distancing myself from the ORM - I should create my own criteria describing classes, and then use those to generate appropriate NHibernate criteria deeper down the stack.
Trevor