开发者

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 reco开发者_JAVA百科rd 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%'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜