Domanda

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?

È stato utile?

Soluzione 3

Never mind -- I stumbled across an earlier StackOverflow post that provided the answer I was looking for, shortly after I posted. Here's my original example rewritten using 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();

Altri suggerimenti

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)

For Restrictions where you want to test equality, use "Where", e.g.:

Restrictions.Where<SomeClass>(x => x.OrderId == order.Id)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top