views:

377

answers:

2

I got a problem whenever I pass char ":" from the user interface. NHibernate mistakes it as a named parameter and throws an error, since there isn't any value for it.

Exception is :-

Not all named parameters have been set: [%] [SELECT COUNT (*) FROM Table t WHERE t.FirstName LIKE ':%' AND t.ID IN (38, 20)]"

Is there any work around?

A: 

You need to escape special characters when using SQL LIKE. Try passing the parameter as @"\" + ":";.

Jamie Ide
Hey..it didn't help...
Novice
Please show the code that calls the query. See also the accepted answer to this question: http://stackoverflow.com/questions/2492984/how-do-i-escape-a-like-clause-using-nhibernate-criteria
Jamie Ide
This is the inner exception after escaping special char....{"Not all named parameters have been set: [%] [SELECT COUNT (*) FROM Table t WHERE t.FirstName LIKE '\\:%']"}
Novice
I was looking for the HQL or Criteria code that is generating the SQL. What database is this? Anyway, it appears I've been leading you astray, this is an NHibernate, not a database, exception. I got a number of hits on it from Google but it's unclear if it's ever been addressed. The workaround is to use named parameters. Here's an example for Castle: http://www.castleproject.org/ActiveRecord/documentation/v1rc1/usersguide/hql.html.
Jamie Ide
+1  A: 

You are probably creating the query in a wrong way (concatenating strings, maybe?)

All of these work:

session.CreateCriteria<Test2>()
       .Add(Restrictions.Like("FirstName", ":%"))
       .UniqueResult<Test2>();

session.CreateQuery("from Test2 where FirstName like :expr")
       .SetParameter("expr", ":%")
       .UniqueResult<Test2>();
Diego Mijelshon
ya you are right actually, preparing adhoc query by concatenating strings...
Novice