NHibernate-使用Criteria API对整数列进行LIKE搜索的最简单方法? [英] NHibernate - easiest way to do a LIKE search against an integer column with Criteria API?
问题描述
我正在尝试对整数列进行类似搜索,实际上,我需要将该列转换为varchar,然后进行类似搜索.这可能吗?使用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. Is this possible? what's the easiest way to do this using the Criteria API?
var search = "123";
criteria.Add(Restrictions.Like("Number", "%" + search + "%"))
推荐答案
如果Number是一个字符串,那将很容易:
If Number were a string, then it would be easy :
.Add(Restrictions.Like("Number", "some_value",MatchMode.Anywhere))
因为有数字,NHibernate会检查Number的类型,如果您给它提供一个字符串,它将抛出异常.
Since you have a number, NHibernate will check the type of Number and if you give it a string it will throw an exception.
不确定NH团队为什么不提供以对象作为参数和MatchMode参数的重载....
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))
修改
关于别名:
(我找不到文档讨论的地方,但这是我对它的理解)
(i can't find where the documentation talks about this but here's my understanding of it )
{alias}返回NH内部为最新CreateCriteria使用的别名.因此,如果您有:
{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}在这种情况下将是'doc'-因此,您最终将得到:doc.Number.
{alias} in this case would be 'doc' - so you would end up with : doc.Number .
因此,请始终在需要使用其别名的CreateCriteria之后使用{alias}.
So, always use {alias} after the CreateCriteria whose alias you need to use.
这篇关于NHibernate-使用Criteria API对整数列进行LIKE搜索的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!