Search code examples
c#nhibernatequeryover

NHibernate ORs using QueryOver


I'm trying to create a simple select with an OR clause using NHibernate 3.3 using QueryOver. So for a simple select like:

Select x,y,z from myTable where x='one' or y = 'two' or z = 'three'

I've come up with this:

IList<MyTable> list = session.QueryOver< MyTable >()
.WhereRestrictionOn(
   Restrictions.Or(Restrictions.On< MyTable >(tab => tab.x == "One"),
                   Restrictions.On< MyTable >(tab => tab.y == "Two") )
 );

It doesn't compile and TBH I suspect I'm going in the wrong direction any way.


Solution

  • This syntax should solve it

    var list = session.QueryOver<MyTable>()
        .Where(
            Restrictions.Or(
              Restrictions.Eq(Projections.Property<MyTable>(tab => tab.x), "One"),
              Restrictions.Eq(Projections.Property<MyTable>(tab => tab.y), "Two")
            )
        )
        .List<MyTable>()
    

    In case we want more, Disjunction is our way to multiple OR:

    var list = session.QueryOver<MyTable>()
        .Where(Restrictions.Disjunction()
          .Add(Restrictions.Eq(Projections.Property<MyTable>(tab => tab.x), "One"))
          .Add(Restrictions.Eq(Projections.Property<MyTable>(tab => tab.x), "Two"))
          .Add(Restrictions.Eq(Projections.Property<MyTable>(tab => tab.x), "xxx"))
        )
        .List<MyTable>()