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

发布于 2024-07-30 08:12:56 字数 203 浏览 7 评论 0原文

我正在尝试对整数列进行类似搜索,我需要做的实际上是将列转换为 varchar,然后进行类似搜索。 这可能吗? 使用 Criteria API 执行此操作的最简单方法是什么?

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

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 + "%"))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蔚蓝源自深海 2024-08-06 08:12:57

如果 Number 是一个字符串,那么就很简单:

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

因为你有一个数字,NHibernate 将检查 Number 的类型,如果你给它一个字符串,它会抛出异常。

不知道为什么 NH 团队没有提供以对象作为参数和 MatchMode 参数的重载...

无论如何,您仍然可以这样做:

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

编辑

关于别名:(

我可以'找不到文档中谈论此问题的位置,但这是我的理解)

{alias} 返回 NH 内部为最近的 CreateCriteria 使用的别名。 因此,如果您有 :

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

{alias} 在这种情况下将是 'doc' - 所以您最终会得到 : doc.Number 。

因此,请始终在需要使用其别名的 CreateCriteria 之后使用 {alias}。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文