问题
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