2011-06-23 117 views
0

我需要製作一個過濾器,以便在sql中的一列表中進行搜索。過濾器在NHibernate的列中搜索

我有兩種方法,第一種接收字符串(Name或LastName)並返回Collection<Employee>

  public ICollection<Employee> GetEmployee_ByName(string Name) 
     { 
      ICollection<Employee> employee; 
      using (ISession session = NHibernateSessionBuilder.OpenSession()) 
      { 
       employee = session.CreateCriteria(typeof(Employee)).Add(Restrictions.Eq("Name", Name)).List<Employee>(); 
       if (employee.Count == 0) 
       { 
       employee = session.CreateCriteria(typeof(Employee)).Add(Restrictions.Eq("LastName", Name)).List<Employee>(); 
       } 
       return employee; 
      } 
      } 

問題是與CreateCriteria(typeof(Employee)).Add(Restrictions.Eq("LastName", Name))如果方法得到的字符串,例如:「老虎伍茲」,並在列姓氏該項目的紀錄是「伍茲泰勒」,不是返回任何結果,因爲這需要有等於列。或者例如「Maikol Smith」,而在專欄中記錄的是「Maikol Smith Jonhson」,它不會返回任何東西。

那麼,在這種情況下我能做些什麼呢?做出好的過濾器。

回答

1

使用等代替公式...

employee = session 
    .CreateCriteria(typeof(Employee)) 
    .Add(Restrictions.Like("LastName", "%" + name + "%")) 

您當前的代碼生成的SQL類似如下:

select ... from ... where LastName = 'Woods' 

使用的,而不是像公式,您生成SQL類似如下:

select ... from ... where LastName like '%Woods%' 
+0

非常好的謝謝! – ale