5

How do I restrict a query by the length of a string property? eg. something like:

NHSession.QueryOver<Customer>()
    .Where(p => p.RegistryCode.Length == 8)
Frédéric
  • 9,364
  • 3
  • 62
  • 112
dänjel
  • 53
  • 4
  • It would be nice if you add a few more details to your question. – Jost Aug 28 '13 at 13:05
  • Don't know what additional detail I could add, it seems a pretty straightforward question to me? – dänjel Aug 28 '13 at 13:30
  • yes your question is not too heavy ;-) - but it contains things like `customer` and a constant (e.g. `8`), which are not further explained. Don't worry it's ok as it is AND you got your answer. – Jost Aug 28 '13 at 13:36

2 Answers2

5

Something like this may do the trick

NHSession.QueryOver<Customer>()
    .Where(
        Restrictions.Eq(
            Projections.SqlFunction("length", NHibernateUtil.String, 
                Projections.Property<Customer>(x => x.RegistryCode)),
            8
        )
    )
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • Thanks, worked, although I had to use "length" instead of "len", as per [this answer](http://stackoverflow.com/questions/9246626/nhibernate-support-the-function-len) – dänjel Aug 28 '13 at 13:29
1

Instead of "NHibernateUtil.String" i should use this "NHibernateUtil.Int16" type, because a 'length' parameter should always be a number and not a String.

Something like this:

NHSession.QueryOver<Customer>()
    .Where(
        Restrictions.Eq(
            Projections.SqlFunction("length", NHibernateUtil.Int16, 
                Projections.Property<Customer>(x => x.RegistryCode)),
            8
        )
    )
Alexander
  • 2,925
  • 3
  • 33
  • 36
Joachim Langezaal
  • 195
  • 1
  • 2
  • 13