NHibernate - easiest way to do a LIKE search against an integer column with Criteria API?

余生长醉 提交于 2019-12-06 19:59:57

问题


I'm trying to do a like search against an integer column, what I need to do is actually cast the column to a varchar and then do the like search. Is this possible? what's the easiest way to do this using the Criteria API?

var search = "123";
criteria.Add(Restrictions.Like("Number", "%" + search + "%"))

回答1:


If Number were a string, then it would be easy :

.Add(Restrictions.Like("Number", "some_value",MatchMode.Anywhere))

Since you have a number, NHibernate will check the type of Number and if you give it a string it will throw an exception.

Not sure why the NH team didn't provide an overload with object as parameter and a MatchMode parameters ....

Anyhow, you can still do it like this :

.Add(Expression.Sql("{alias}.Number like ?", "%2%", NHibernateUtil.String))

Edit

About the alias :

(i can't find where the documentation talks about this but here's my understanding of it )

{alias} returns the alias used inside by NH for the most recent CreateCriteria. So if you had :

session.CreateCriteria<User>("firstAlias")
       .CreateCriteria("firstAlias.Document", "doc")
       .Add(Expression.Sql("{alias}.Number like ?", "%2%",  
                           NHibernateUtil.String)).List<User>();

{alias} in this case would be 'doc' - so you would end up with : doc.Number .

So, always use {alias} after the CreateCriteria whose alias you need to use.



来源:https://stackoverflow.com/questions/1231054/nhibernate-easiest-way-to-do-a-like-search-against-an-integer-column-with-crit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!