give parameters in sql expression in NHibernate

只谈情不闲聊 提交于 2019-12-12 23:18:35

问题


I want to use collation in a query in NHibernate and apparently the only way to do that (at least from what I found) is through adding an sql expression (Can I customize collation of query results in nHibernate?)

So I have something like

c.Add(Expression.Sql("Title COLLATE Divehi_90_BIN2 LIKE ?", 
                     title, 
                     NHibernateUtil.String))

However this matches the exact string and I want to use % on both sides.

Title COLLATE Divehi_90_BIN2 LIKE %?% gives me an error,

but padding it on the title: "%" + title + "%" works.

My question is - Is there a way to properly give parameters in Expression.Sql because using the % on both sides looks like a security flaw - that I am inviting query injection.

PS. I can't change the collation of the column at the database level because the column contains data that are of two languages.


回答1:


The problem is that %@p0% is not a quoted string, i.e. '%@p0%'.

From the NHibernate documentation it seems this is the recommended form.

Expression.Sql("Title COLLATE Divehi_90_BIN2 LIKE ?", 
               String.Format("%{0}%", title),
               NHibernateUtil.String)

Please note that the string String.Format("%{0}%", title) will be passed in as a parameter so you are not inviting sql injection attacks by this approach.



来源:https://stackoverflow.com/questions/16183167/give-parameters-in-sql-expression-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!