views:

80

answers:

2

Hi, small questions about Restrictions.

i have query like this :

Where  A in(1,6) and (B not like 'Value%' or B not like 'ValueII%')

the problem is the field B not contains a fixed value, can be one or more.

Please, (N)Hibernate experts - help me with this, I cant find a working solution. Any help is greatly appreciated!

+2  A: 

You can use disjunctions to handle the OR cases, as such:

IList results = session.CreateCriteria(typeof(MyType))
    .Add(Restrictions.In("A", new [] {1, 6}))
    .Add(Restrictions.Disjunction()
        .Add.Restrictions.Not(Restrictions.Like("B", "Value%"))
        .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%")))
    .List<MyType>();

If you need to handle the disjunction conditions in a for loop (per your follow-up), you can use code like this:

ICriteria query = session.CreateCriteria(typeof(MyType));
query.Add(Restrictions.In("A", new [] {1, 6}))

Disjunction disjunction = Restrictions.Disjunction();
foreach (var value in values) {
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "Value%")));
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "ValueII%")));
}
query.Add(disjunction);

IList results = query.List<MyType>();

That being said, I think there may be a flaw in your logic. If you are testing these values to "not match one pattern OR not match another pattern", then the condition will always evaluate to true (unless the patterns are the same). Are you sure you want to be using ORs here?

Ben Hoffstein
A: 

the problem is that I don't know exact how many restrictions i have and i need to use FOR in disjunction.

Something like that:

IList results = session.CreateCriteria(typeof(MyType))
.Add(Restrictions.In("A", new [] {1, 6}))
.Add(Restrictions.Disjunction());
 for(int i = 0, i < value.Lenght;i++){
    .Add.Restrictions.Not(Restrictions.Like("B", "Value%"));
    .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%"));
 }
.List<MyType>();

thanks for you help

Wesley
See my edited answer above.
Ben Hoffstein