查询StartsWith

时间:2014-06-30 08:13:03

标签: nhibernate queryover

我必须尝试根据搜索结果找到结果,这应该是从头开始的,但是我找不到以{1}开头的那个,还有其他的吗?

QueryOver

1 个答案:

答案 0 :(得分:8)

QueryOver基础架构支持的方式是使用显式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>();

但是使用极少数代码Restrictions.On样式中的自定义扩展程序),我们甚至可以实现此语法:

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

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);
        }
    }
}