NHibernate 与整数类似
我有一个 NHibernate 搜索函数,我在其中接收整数并希望返回至少开头与整数一致的结果,例如
接收到的整数:729
返回:729445、7291 等。
数据库列的类型为 int,Foo 的属性“Id”也是如此。
但
int id = 729;
var criteria = session.CreateCriteria(typeof(Foo))
criteria.Add(NHibernate.Criterion.Expression.InsensitiveLike("Id", id.ToString() + "%"));
return criteria.List<Foo>();
确实会导致错误(无法将参数字符串转换为 int32)。代码、解决方法或其他解决方案是否有问题?
I have a NHibernate search function where I receive integers and want to return results where at least the beginning coincides with the integers, e.g.
received integer: 729
returns: 729445, 7291 etc.
The database column is of type int, as is the property "Id" of Foo.
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). Is there something wrong in the code, a work around, or other solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个怎么样:
How about this:
您是否尝试过这样的事情:
这个想法是在使用 to_char 函数之前转换列。有些数据库会自动执行此操作。
Have you tried something like this:
The idea is convert the column before using a to_char function. Some databases do this automatically.
AFAIK,如果您想使用内置的 NHibernate 功能,您需要将整数作为字符串存储在数据库中(即使没有 NHibernate,我也会推荐这种方法 - 当您开始执行“类似”搜索时,您正在处理使用字符串,而不是数字 - 想想美国邮政编码等...)。
您还可以在特定于数据库的函数中以数学方式执行此操作(或转换为字符串,如 蒂亚戈·阿泽维多的回答),但我想这些选项会明显变慢,并且还有可能将您与特定数据库联系起来。
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...).
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.