Search code examples
c#nhibernatenhibernate-criteria

ICriteria adding Or Restrictions


I need to do a select as follows

select * from produtos where Value = 10 or Value = 15 or  Value= 20 ....

being that I do not know how many values ​​will come, it will be in a loop on a list that the user will decide how many values ​​will be ... the problem is that if I do Criteria

ICriteria criterion = session.createCriteria(typeof (Product) "produto"). SetCacheable (true);
criterio.Add (Restrictions.Eq ("produto.Valor", 10));
criterio.Add (Restrictions.Eq ("produto.Valor", 15));
criterio.Add (Restrictions.Eq ("produto.Valor", 20));

is made with a select clause "and"

select * from produtos where Value=10 and Value = 15 and  Value= 20 ....

can not use the Restriction "in" because I can have place in the Restrictions.Eq Restrictions.Ge or Restrictions.Le or any other clause ...

There is some way to go just adding clauses in Criteria? something like

criteria.Add (Restrictions.Or (Restrictions.Eq ("produto.Valor", 10)));
criteria.Add (Restrictions.Or (Restrictions.Eq ("produto.Valor", 15)));
criteria.Add (Restrictions.Or (Restrictions.Eq ("produto.Valor", 20)));
criteria.Add (Restrictions.Or (Restrictions.Eq ("produto.Valor", 25)));

I understand that it uses some kind of expression like link but did not understand how this could help me to go riding a select, for example, say I have a foreach and for each item I need to get this foreach adding an "or" in the criteria,

foreach (var item in items)
{
    criteria.Add("or item.Valor =" item.Valor);
}

I can only criteria in this:

foreach (var item in items)    
{
    criteria.Add(Restrictions.Eq("item.Valor", item.Valor));
}

What would a "and" or it. But that would not or could add another criteria to that.

I would have wanted that over the same situations

foreach (var item in items)
{
    var items = session.QueryOver<Item>()
                       .WhereRestrictionOn(c => c.Valor item.Valor == | |?)
                       .List<Item>();
}

Solution

  • Maybe you can try :

    criteria.Add (
        new Disjunction()
            .Add (Restrictions.Eq ("produto.Valor", 10))
            .Add (Restrictions.Eq ("produto.Valor", 15))
            .Add (Restrictions.Eq ("produto.Valor", 20))
            .Add (Restrictions.Eq ("produto.Valor", 25))
        );
    

    I guess criteria.Add (Restrictions.In("produto.Valor", new[]{10,15,20,25}); should also work

    Hope this will help