Search code examples
linqnhibernatefluent-nhibernate

(Fluent)NHibernate SELECT IN


Given the following tables:

tool
 *toolid
 *n other fields

process
 *processid
 *n other fields

toolprocess
 *toolprocessid
 *toolid
 *processid
 *n other fields

When trying to select all tools for a specific process I get up to a few thousand selects on toolprocess where my Linq looks like this:

from tool in tools
where toolprocesses.Any(t=>t.Tool.Id==tool.Id)
select tool

where toolprocesses contains the list of toolprocesses with the same processid

In SQL I would just write

SELECT * FROM TOOL WHERE toolid IN 
    (SELECT TOOLID FROM TOOLPROCESS WHERE processid = 'someid');

It takes almost no time and works as expected

How can I get NHibernate to create this query (or something similar)?


Solution

  • Try

    from t in Session.Query<Tool>()
    join tp in Session.Query<Toolprocess>() on t equals tp.Tool
    where tp.Process.Id == 'someid'
    select t;
    

    I assume that you're using NH 3.X. This should be even faster than the Select...Where...In query.