Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Although Diego's answer is the accepted method for doing these things in NHibernate, I really don't feel comfortable with that approach. I don't want to have to define explicit contracts for my objects just because I may need to retrieve them in certain ways. Also, I don't always want to serialize them at all. Furthermore, in many cases I know that the best performance will <em>always</em> be a single round-trip to fetch all the data.</p> <p>The solution I ended up using was to implement a function that takes a list of (type safe) expressions on the root object, such as</p> <pre><code>x =&gt; x.Child.GrandChild1 x =&gt; x.Child.GrandChild2Collection.SubInclude(c =&gt; c.GreatGrandChild) </code></pre> <p>Where SubInclude is an extension method for IEnumerable that is used when parsing these expressions.</p> <p>I parse this list of expressions and build, for each subpath of each expression (x, x.Child, x.Child.GrandChild1) an NHibernate criteria query on the root type:</p> <pre><code>var queryOver = session.QueryOver&lt;T&gt;().Where( ...expression to select root objects... ); for every subpath in the current expression: queryOver.RootCriteria.SetFetchMode(subPath, FetchMode.Eager) queryOver.RootCriteria .SetResultTransformer(new DistinctRootEntityResultTransformer()) queryOver.Future() </code></pre> <p>This is repeated for every expression in the list. The last line makes sure that this eager fetch will be included in whatever round-trip happens next. Then I make the actual query on the root object T, and the session automatically performs in that same round-trip all the queries required to fetch each of the paths I've passed in the expressions.</p> <p>The queries are performed separately for each expression path, so there is no cartesian-product problem.</p> <p><strong>Bottom line</strong> is that this is no simple feat. There's a little too much code for me to publish as-is. I prefer EF4.1's Include(expression) API, which does all of this automagically.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload