Quoting identifiers in NHibernate

I was doing some work with NHibernate today and encountered the following problem which made me cranky for a few minutes, but Google provided an answer for my woes, so I thought I would share it.

It is generally inadvisable to create table columns with names that also happen to be reserved keywords.  Sometimes this is unavoidable, however, especially since SQL Server reserves common words like “File” and “Description”.  I know this, because when I attempted to execute an NHibernate query with those column names, I got this nastygram from NHibernate:

SELECT … this_.File as File2_0_, … FROM … this_

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword ‘File’…

Some diligent internet scouring revealed that NHibernate can be instructed to quote columns by wrapping column names with the backtick ( ` ) symbol in the appropriate hbm.xml file, like so:

<property name=”File” column=”`File`” not-null=”true” />

The generated query executed flawlessly.

SELECT … this_.[File] as File7_2_0_, … FROM … this_

Leave a Reply

Your email address will not be published. Required fields are marked *