简体   繁体   English

NHibernate - 使用Criteria API对整数列进行LIKE搜索的最简单方法?

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

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. 我正在尝试对整数列进行搜索,我需要做的是实际将列转换为varchar然后执行类似搜索。 Is this possible? 这可能吗? what's the easiest way to do this using the Criteria API? 使用Criteria API最简单的方法是什么?

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

If Number were a string, then it would be easy : 如果Number是一个字符串,那么很容易:

.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. 由于你有一个数字,NHibernate将检查Number的类型,如果你给它一个字符串,它将抛出一个异常。

Not sure why the NH team didn't provide an overload with object as parameter and a MatchMode parameters .... 不确定为什么NH团队没有提供带对象的重载作为参数和MatchMode参数....

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. {alias}返回NH内部用于最新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 . 在这种情况下,{alias}将是'doc' - 所以你最终会得到:doc.Number。

So, always use {alias} after the CreateCriteria whose alias you need to use. 因此,请始终在需要使用其别名的CreateCriteria之后使用{alias}。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM