nhibernate : Selecting a static string from DB(Oracle) via NamedParameter or PositionalParameter
In order to validate what our oracle database would give us when we feed it with Unicode, we use a simple trick : selecting the string from dual. That runs the Database encoding over the string.
select 'Let’s Go' from dual
Now I want to implement the very same thing using NHibernate. Merely doing this :
string.Format("select '{0}' from dual", text);
leaves my code brittle and open to SQL injections, so I'd rather do one of the following:
//Version 1 : Named param
IQuery q = this.Session.CreateSQLQuery( "SELECT :staticstring from dual");
q.SetString(":staticstring", text);
// Version 2 : positional param
IQuery q = this.Session.CreateSQLQuery( "SELECT ? from du开发者_如何学Cal");
q.SetString(0, text);
Both of the abovementioned ways fail, the param cannot be assigned. I thought this was an issue with putting parameters anywhere before the 'from'-clause, but that turned out to work when I tried without NH. BTW, I tried both Oracle9 and 10 dialect.
Is there any other way I can safely select a static string from my oracle Database using NHibernate 2.1? Florian suggested QueryOver, but that's new in 3.0...
SOLUTION (Based on Florian's and Phill's input):
DetachedCriteria crit = DetachedCriteria.For<Freetext>()
.SetProjection(Projections.Cast(NHibernateUtil.String,Projections.Constant(text)))
.SetMaxResults( 1 );
string dbString = crit.GetExecutableCriteria( this.Session ).List < object >()[0].ToString();
This might be a little overkill, but it gets the job done:
string text = "Let's go";
var result = session.QueryOver<SomeTable>()
.Select(Projections.Cast(NHibernateUtil.String, Projections.Constant(text)))
.Take(1)
.List<object>();
string s = result[0] as string;
精彩评论