2014-06-30 177 views
4

我必須嘗試查找基於搜索的結果,這應該是首發,但我找不到QueryOver其中有startwith,有沒有其他方法?查詢結束開始與

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>(); 
} 
+1

你的意思是除了刪除IsLike限制中的前導%嗎? – jbl

回答

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