Query Over StartsWith
Asked Answered
C

1

6

I have to try finding results based on search, which should be startswith, but I cannot find QueryOver which has startswith, is there any otherway ?

public IEnumerable<Company> Find(string keyword)
{
     var sesion = SessionController.CurrentSession;
     return sesion.QueryOver<Company>()
     .Where(
        Restrictions.On<Company>(x => x.CompanyName).IsLike("%" + keyword + "%") ||
        Restrictions.On<Company>(x => x.Id).IsLike("%" + keyword + "%")
     )
     .List<Company>();
}
Cant answered 30/6, 2014 at 8:13 Comment(1)
You mean any other way than removing the leading % in your IsLike restrictions ?Chevy
I
11

The way, supported by QueryOver infrastructure would be to use explicit MatchMode:

sesion
  .QueryOver<Company>()
  .Where
  (
     Restrictions.On<Company>(x => x.CompanyName).IsLike(keyword, MatchMode.Start) ||
     Restrictions.On<Company>(x => x.Id         ).IsLike(keyword, MatchMode.Start)
  )
  .List<Company>();

But with a very few code (custom extension in the Restrictions.On style) we can even achieve this syntax:

...
.Where
(
   Restrict.On<Contact>(x => x.CompanyName).StartsWith(keyword) ||
   Restrict.On<Contact>(x => x.Id         ).StartsWith(keyword)
)

And the definition of the Restrict:

public static class Restrict
{
    public static StringRestrictionBuilder<T> On<T>(Expression<Func<T, object>> expr)
    {
        return new StringRestrictionBuilder<T>(expr);
    }
    public class StringRestrictionBuilder<T>
    {
        readonly Expression<Func<T, object>> _expression;
        public StringRestrictionBuilder(Expression<Func<T, object>> expression)
        {
            _expression = expression;
        }
        public AbstractCriterion StartsWith(string value)
        {
            return Restrictions.On(_expression).IsLike(value, MatchMode.Start);
        }
        public AbstractCriterion Contains(string value)
        {
            return Restrictions.On(_expression).IsLike(value, MatchMode.Anywhere);
        }
        public AbstractCriterion EndsWith(string value)
        {
            return Restrictions.On(_expression).IsLike(value, MatchMode.End);
        }
    }
}
Idaidae answered 30/6, 2014 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.