7

Is there a way to tell NHibernate to use square brackets for all table and column names (like [MyColumn]) when generating the SQL schema export for MS SQL Server? I have a legacy database that uses reserved names for certain columns and running the SQL script generated using NH throws an error because of it.

I want to avoid having to specify this separately for each column.

UPDATE: I'm using the correct dialect:

MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)

UPDATE 2: @UpTheCreek pointed me in the right direction - backticks, which helped me find the answer in the "NHibernate in Action" book (p. 76):

There is no way, apart from quoting all table and column names in backticks, to force NHibernate to use quoted identifiers everywhere.

1
  • You could write a custom dialect. But personally, I'd just add the backticks manually ;)
    – UpTheCreek
    Nov 5, 2010 at 9:44

3 Answers 3

12

Easier approach:

SchemaMetadataUpdater.QuoteTableAndColumns(config)

(Before building SessionFactory)

That will quote all the reserved names automatically.

3
  • There seem to be a better solution here: stackoverflow.com/questions/2438491/…
    – Nux
    Sep 9, 2011 at 12:53
  • @Nux: why do you think it's better? Sep 9, 2011 at 13:51
  • Better in terms of completness and it also seems to only escape what is needed to be escaped (keywords).
    – Nux
    Sep 9, 2011 at 15:27
2

Use backticks in your mapping files around the column names. NH should replace these with the correct character for your db dialect (in your case square brackets).

i.e. use:

<class name="SomeClass" table="`SomeTable`">

NB - It won't work with an apostrophe. The backtick is located top left on most keyboards.

5
  • I'm actually using Fluent NH, but I've tried it and backticks work there too. Although it doesn't really do what I asked for (a general approach and not having to do it separately for each name), I'll accept your answer since it pointed me to a page in the NH in Action book where the answer lies. Thanks
    – Igor Brejc
    Nov 5, 2010 at 9:37
  • @Igor: Did you find a general approach? I would have though you would need to customise the dialiect for that.
    – UpTheCreek
    Nov 5, 2010 at 9:40
  • @UpTheCreek: see my updated question. Yes, I presume (over)writing the dialect would do the trick, but I guess backticks are a simpler solution for my current problem :)
    – Igor Brejc
    Nov 5, 2010 at 9:42
  • @Igor, yeah, seems a little extreme! :)
    – UpTheCreek
    Nov 5, 2010 at 9:45
  • 1
    @Igor if you're using Fluent NH, see: Conventions Nov 5, 2010 at 13:13
0

You need to use (or write) the correct dialect for your database

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.