Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The version of LINQ-to-NHibernate that is compatible with NH 2.1.2 does not support querying by type at runtime.</p> <pre><code>// DOES NOT WORK WITH NH 2.1.2 &amp; LINQ-to-NH var desiredType = typeof(Cat); var query = from animal in session.Linq&lt;Animal&gt;() where animal.Color == "White" &amp;&amp; animal.GetType() == desiredType select animal; // This results in an ArgumentOutOfRangeException in the LINQ provider </code></pre> <p>You can do this in-memory as suggested in the comments:</p> <pre><code>var desiredType = typeof(Cat); var query = from animal in session.Linq&lt;Animal&gt;() where animal.Color == "White" select animal; var animals = query.ToList(); var whiteCats = from animal in animals.AsQueryable() where animal.GetType() == desiredType select animal; </code></pre> <p>By performing query.ToList(), you are reading back all white animals and then performing the type-query using LINQ-to-Objects. (Depending on your exact query and mapping, you may have to worry about lazy proxies and therefore check if the object's type is assignable to the desiredType.) This does have the major disadvantage of reading back more data than needed in order to filter by animal type in memory. Depending on your domain and the query, this may or may not be a big issue.</p> <p>If you cannot upgrade to NHibernate trunk (aka NH3), I would recommend not using LINQ-to-NHibernate for this query and instead using Criteria.</p> <pre><code>var desiredType = typeof(Cat); var query = session.CreateCriteria(desiredType) .Add(Restrictions.Eq("Color", "White") .List&lt;Animal&gt;(); </code></pre> <p>N.B. It should be obvious, but let me just state it explicitly. There is no reason that you can't use Criteria for this query and LINQ-to-NHibernate for your other queries. You can mix-an-match query techniques in NHibernate freely.</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