Filter to search in a column with NHibernate

I need to make a filter to search in a column of a table in sql.

I have two methods, the first one receive a string(Name or LastName) and return a 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;
            }
          }

The problem is with CreateCriteria(typeof(Employee)).Add(Restrictions.Eq("LastName", Name)) if the method receive a string for example: "Woods" and in the Column LastName the record for this Item is "Woods Taylor" that not return nothing, because that need are Equal to the column.

Or for example "Maikol Smith" and in the column the record is "Maikol Smith Jonhson" that not return nothing.

So, what can I do in this case?. To make a good filter.


Use Like instead of Eq...

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

Your current code generates SQL like the following:

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

By using Like instead of Eq, you generate SQL like the following:

select ... from ... where LastName like '%Woods%'
链接地址: http://www.djcxy.com/p/37094.html

上一篇: 从grails域的属性获取数据库列名称

下一篇: 用NHibernate过滤在列中搜索