Note that there are some explanatory texts on larger screens.

plurals
  1. POSet operations in predicates passed to NHibernate's Criteria API
    text
    copied!<p>In the project I am working on, we are passing a specification (ala the Specification pattern as put forward by Martin Fowler) to a repository that uses NHibernate as its backend. The predicates to determine whether a given object are implemented as lambdas wrapped as Expressions, which the repository hands off to the Criteria API in NHibernate to actually fetch the result.</p> <p>What we have looks something like:</p> <pre><code>class MySpecification : ISpecification&lt;AnEntity&gt; { public Expression&lt;Func&lt;AnEntity, bool&gt;&gt; Satisfies { get { return entity =&gt; entity.Children.Count(c =&gt; !c.IsDeleted) == 0; } } } </code></pre> <p>and in the repository:</p> <pre><code>public IEnumerable&lt;AnEntity&gt; Select(ISpecification&lt;AnEntity&gt; spec) { ICriteria criteria = Session.CreateCriteria&lt;AnEntity&gt;(); criteria.Add(NHibernate.Criterion.Expression.Where(spec.Satisfies)); return criteria.List&lt;AnEntity&gt;(); } </code></pre> <p>At runtime, we get exceptions of the form: </p> <pre><code>{variable 'entity' of type 'AnEntity' referenced from scope '', but it is not defined"} System.Exception {System.InvalidOperationException} </code></pre> <p>When we reduce the predicates to simple boolean expressions that perform no set operations (e.g. Any, Count, Where) on child collections, everything works fine. </p> <p>With that in mind, is there any way to build a criterion using a lambda expression that operates on the child collections of the main entity?</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