简体   繁体   English

NHibernate和整数一样

[英]NHibernate Like with integer

I have a NHibernate search function where I receive integers and want to return results where at least the beginning coincides with the integers, eg 我有一个NHibernate搜索函数,我接收整数并希望返回结果,其中至少开始与整数重合,例如

received integer: 729 收到整数:729
returns: 729445, 7291 etc. 返回:729445,7291等

The database column is of type int, as is the property "Id" of Foo. 数据库列的类型为int,Foo的属性“Id”也是如此。

But

int id = 729;

var criteria = session.CreateCriteria(typeof(Foo))

criteria.Add(NHibernate.Criterion.Expression.InsensitiveLike("Id", id.ToString() + "%"));

return criteria.List<Foo>();

does result in an error (Could not convert parameter string to int32). 确实导致错误(无法将参数字符串转换为int32)。 Is there something wrong in the code, a work around, or other solution? 代码,解决方法或其他解决方案是否有问题?

How about this: 这个怎么样:

int id = 729;

var criteria = session.CreateCriteria(typeof(Foo))
criteria.Add(Expression.Like(Projections.Cast(NHibernateUtil.String, Projections.Property("Id")), id.ToString(), MatchMode.Anywhere));

return criteria.List<Foo>();

AFAIK, you'll need to store your integer as a string in the database if you want to use the built in NHibernate functionality for this (I would recommend this approach even without NHibernate - the minute you start doing 'like' searches you are dealing with a string, not a number - think US Zip Codes, etc...). AFAIK,你需要将整数作为字符串存储在数据库中,如果你想使用内置的NHibernate功能(即使没有NHibernate,我也会推荐这种方法 - 你开始做的那一刻'就像'搜索你正在处理用字符串,而不是数字 - 想想美国邮政编码等...)。

You could also do it mathematically in a database-specific function (or convert to a string as described in Thiago Azevedo's answer ), but I imagine these options would be significantly slower, and also have potential to tie you to a specific database. 您也可以在数据库特定的函数中进行数学处理(或转换为Thiago Azevedo的答案中描述的字符串),但我想这些选项会明显变慢,并且还有可能将您绑定到特定的数据库。

Have you tried something like this: 你尝试过这样的事情:

int id = 729;

var criteria = session.CreateCriteria(typeof(Foo))

criteria.Add(NHibernate.Criterion.Expression.Like(Projections.SqlFunction("to_char", NHibernate.NHibernateUtil.String, Projections.Property("Id")), id.ToString() + "%"));

return criteria.List<Foo>();

The idea is convert the column before using a to_char function. 我们的想法是在使用to_char函数之前转换列。 Some databases do this automatically. 有些数据库自动执行此操作

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

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