开发者

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, 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 th开发者_开发问答ere 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>();


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. Some databases do this automatically.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜