NHibernate: Conjunctions and Decouples Using QueryOver

Say I have an SQL query that needs to be executed using nHibernate. The SQL WHERE clause consists of three OR statements, each of which contains a list of conditions. For instance:

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

Using the nHibernate 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 to write the same type of query using the QueryOver syntax in nHibernate 3.x?

+4
source share
3 answers

Nothing, I came across fooobar.com/questions/1345738 / ... , which provided the answer I was looking for shortly after I posted. Here's my original example rewritten using the QueryOver syntax:

 var disjunction = Restrictions.Disjunction(); foreach (var tuple in OrdersAndLineItems) { var conjunction = Restrictions.Conjunction(); var order = tuple.Item1; var lineitem = tuple.Item2; conjunction.Add(Restrictions.On<SomeClass>(x => x.OrderId).Equals(order.Id)); conjunction.Add(Restrictions.On<SomeClass>(x => x.LineItemId).Equals(lineitem.Id)); disjunction.Add(conjunction); } var result = Session.CreateCriteria<SomeClass>().Add(disjunction).ToList(); 
-3
source

There are several overloaded Add methods, at least in NH version 3.0.0.4000. One of them has a common parameter that can be used for your case, for example:

 disjuction.Add<TypeinWhichPrimaryKeyPropertyExists>(x => x.PrimaryKey == 1) 
+1
source

For restrictions in which you want to check for equality, use Where, for example:

 Restrictions.Where<SomeClass>(x => x.OrderId == order.Id) 
0
source

All Articles