IHave the following NHibernate query using a subquery:
NHContext.Session.QueryOver<Item>() .WithSubquery.WhereProperty(x => x.ItemId).In(QueryOver.Of<Foo>().Where(x => x.AFlag).Select(x => x.ItemId)) .WithSubquery.WhereProperty(x => x.ItemId).In(QueryOver.Of<Bar>().Where(x => x.AFlag).Select(x => x.Item)) .Future<Item>();
This runs the following SQL:
SELECT * FROM item this_ WHERE this_.ItemId in (SELECT this_0_.ItemId as y0_ FROM Foo this_0_ WHERE this_0_.AFlag = 1 /* @p0 */) and this_.ItemId in (SELECT this_0_.ItemId as y0_ FROM Bar this_0_ WHERE this_0_.AFlag = 1 /* @p0 */)
I would like it to use OR so for example:
SELECT * FROM item this_ WHERE this_.ItemId in (SELECT this_0_.ItemId as y0_ FROM Foo this_0_ WHERE this_0_.AFlag = 1 /* @p0 */) or this_.ItemId in (SELECT this_0_.ItemId as y0_ FROM Bar this_0_ WHERE this_0_.AFlag = 1 /* @p0 */)
I know I can do it in Criteria by doing something like:
var disjunction = new Disjunction(); disjunction.Add(Subqueries.PropertyIn("ItemId", DetachedCriteria.For<Foo>() .SetProjection(Projections.Property("ItemId")) .Add(Restrictions.Eq("AFlag", 1)) ));
But was wondering if there was an easier way to do it via QueryOver, and avoiding using strings for property names.
Thanks for any help.
QueryOver is a strongly-typed version of Criteria, and is more NHibernate specific. Pretty much anything you can do in ICriteria can be done with QueryOver.
Subquery in HAVING Clause A subquery in the HAVING clause helps in filtering the groups for the result set, by comparing a column in the main table with the results of the subquery.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.
A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator, such as IN, ANY, or ALL.
For the less common disjunction(or) I think you need to use the Subqueries.WhereProperty<>
instead of WithSubquery
Session.QueryOver<Item>() .Where(Restrictions.Disjunction() .Add(Subqueries.WhereProperty<Item>(x => x.ItemId).In(QueryOver.Of<Foo>().Where(x => x.AFlag).Select(x => x.ItemId))) .Add(Subqueries.WhereProperty<Item>(x => x.ItemId).In(QueryOver.Of<Bar>().Where(x => x.AFlag).Select(x => x.Item)))) .Future<Item>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With