score:0

Perhaps not exactly what you're after, but certainly worth considering is the NHibernate.CollectionQuery library.

It allows you to query uninitialized NHibernate collections on an entity using Linq - but would require an additional query/round-trip to get them (unlike FetchMany, which grabs the entire collection in the same round-trip).

score:0

You will need a reference from child object to the parent.

var result = from foo in session.Query<Foo>().FetchMany(f => f.Bars)
             from bar in session.Query<Bar>()
             where foo.Id == bar.FooId && // FooId is missing in your entity
                   foo.Id > 30
                   bar.Description.StartsWith("x")
             select foo;

score:1

I'm fairly sure you're out of luck with the current linq provider - but for a non-linq (and cross-cutting) option, you might want to have a look at the filter functionality included in NHibernate - it would probably be the best bet for implementing this in a large scale / complex project.

score:1

var query = from foo in session.Query<Foo>()
            where foo.Id >30
            from bar in foo.Bars
            where bar.Description.StartsWith("x")
            select new { Id = foo, Bar = bar};
var results = query.ToList().ToLookup(x => x, x => x.Bar);
foreach(var foo in results.Keys)
{
   var barsWhichStartWithX = results[foo];
   //DO STUFF
}

Although this may produce inefficient SQL (I don't use nHibernate so I wouldn't know). You could also try this...Also the above would miss out foos without bars.

var foosQuery = session.Query<Foo>().Where(foo => foo.Id > 30);
var foos = foosQuery.Future();
var barsQuery = from f in foosQuery
                from bar in foo.Bars
                select new { Id = foo.Id, Bar = bar};
var foosDict = foos.ToDictionary(x => x.Id);
var bars = barsQuery.ToList().ToLookup(x => foosDict[x.Id], x => x.Bar);
foreach(var foo in foos)
{
   var barsWhichStartWithX = bars[foo];
   //DO STUFF
}

Related Articles