简体   繁体   中英

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

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?

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...).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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