Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate, get grandchildren collection using QueryOver w/ Future

Tags:

c#

nhibernate

I'm trying to retrieve all collections (non-cartesian product) of a parent entity, but can't figure out how to get the grandchildren. Table structure looks like:

enter image description here

The following code gets my parent and its Child1 and Child2 collections, as well as its ParentChild3 collection, but I do not know how to structure the query to get the Child3 grandchildren (and defer them to Future()).

var parent = _session
    .QueryOver<Parent>()
    .Where(x => x.Id == id)
    .Future<User>();

var children1 =_session
    .QueryOver<Parent>()
    .Where(x => x.Id == id)
    .Fetch(x => x.Children1).Eager
    .Future<Parent>();

var children2 =_session
    .QueryOver<Parent>()
    .Where(x => x.Id == id)
    .Fetch(x => x.Children2).Eager
    .Future<Parent>();

var parentChildren3 =_session
    .QueryOver<Parent>()
    .Where(x => x.Id == id)
    .Fetch(x => x.ParentChildren3).Eager
    .Future<Parent>();

// how to get children3, now?

return parent.SingleOrDefault();

Semi-related: is this the best way to get all collections? Is it better (and possible) to use a query that obtains the result with joins instead?

like image 638
heyseuss Avatar asked Oct 08 '22 02:10

heyseuss


1 Answers

how to get Children3:

ParentChildren alias = null;
var parentChildren3 =_session
    .QueryOver<Parent>()
    .Where(x => x.Id == id)
    .JoinAlias(x => x.ParentChildren3, () => alias)
    .Fetch(() => alias.Children3).Eager
    .Future<Parent>();

Semi-related: It is the best way i know of.

If the ParentChild table does not have additional columns then you could map it as standard manytomany. NHibernate won't need entities for the link table then and the eager fetching will be easier.

like image 52
Firo Avatar answered Oct 10 '22 07:10

Firo