NHibernate: Conjunctions and Disjunctions using QueryOver

nhibernatenhibernate-criteriaqueryover

Let's say I have a SQL query I need to render using nHibernate. The SQL query's WHERE clause consists of three OR statements, each of which contains a list of conditions. For example:

SELECT * 
FROM MyTable 
WHERE
    (OrderId = 1 and ItemId = 100) 
    OR
    (OrderId = 2 and ItemId = 200)
    OR
    (OrderId = 3 and ItemId = 300)

Using nHibernate's Criteria syntax, I could use a disjunction to implement this:

var disjunction = Restrictions.Disjunction();

foreach (var tuple in OrdersAndLineItems)
{
    var conjunction = Restrictions.Conjunction();
    var order = tuple.Item1;
    var lineitem = tuple.Item2;

    conjunction.Add(Restrictions.Eq("OrderId", order.Id));
    conjunction.Add(Restrictions.Eq("LineItemId", lineitem.Id));

    disjunction.Add(conjunction);
}

var result = Session.CreateCriteria<SomeClass>().Add(disjunction).ToList();

How would I write the same type of query using the QueryOver syntax in nHibernate 3.x?

Best Answer

There are multiple overloaded of Add method at least in NH version 3.0.0.4000. One of them is having generic parameter that can be used for your case, for example:

disjuction.Add<TypeinWhichPrimaryKeyPropertyExists>(x => x.PrimaryKey == 1)
Related Topic