Nhibernate Criteria 多个or条件查询

时间:2022-06-23 22:26:02

sql: select * from table t where (t.name like '%张三%' or t.schoolName like '%张三%' or t.cityname like '%张三%')

 

用Nhibernate Criteria就可以写成

 var criteria = NHibernateSessionReader.CreateCriteria(typeof(Contract));

            if (!string.IsNullOrEmpty(keyWord))
            {

      criteria.Add(Expression.Like("name", keyWord, MatchMode.Anywhere)
                       || Expression.Like("school", "%" + keyWord + "%")
                       || Expression.Like("cityname", "%" + keyWord + "%")                    
                       || Expression.Like("province", "%" + keyWord + "%")
                       || Expression.Like("UserName", "%" + keyWord + "%")); 

     }

或者

    if (!string.IsNullOrEmpty(keyWord))
            {

     criteria.Add(
                    Restrictions.Or(Expression.Like("name", keyWord, MatchMode.Anywhere),
                    Restrictions.Or(Expression.Like("school", keyWord, MatchMode.Anywhere),
                    Restrictions.Or(Expression.Like("cityname", keyWord, MatchMode.Anywhere),
                    Restrictions.Or(Expression.Like("province", keyWord, MatchMode.Anywhere),
                    Restrictions.Or(Expression.Like("UserName", keyWord, MatchMode.Anywhere),
                    Restrictions.Like("UserName", keyWord, MatchMode.Anywhere)))))));

    }