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.

Igor Brejc
  • 18,714
  • 13
  • 76
  • 95

3 Answers3

12

Easier approach:

SchemaMetadataUpdater.QuoteTableAndColumns(config)

(Before building SessionFactory)

That will quote all the reserved names automatically.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • There seem to be a better solution here: http://stackoverflow.com/questions/2438491/fluent-nhibernate-and-postgresql-schemametadataupdater-quotetableandcolumns-sy – Nux Sep 09 '11 at 12:53
  • @Nux: why do you think it's better? – Diego Mijelshon Sep 09 '11 at 13:51
  • Better in terms of completness and it also seems to only escape what is needed to be escaped (keywords). – Nux Sep 09 '11 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.

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
  • 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 05 '10 at 09:37
  • @Igor: Did you find a general approach? I would have though you would need to customise the dialiect for that. – UpTheCreek Nov 05 '10 at 09: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 05 '10 at 09:42
  • @Igor, yeah, seems a little extreme! :) – UpTheCreek Nov 05 '10 at 09:45
  • 1
    @Igor if you're using Fluent NH, see: [Conventions](http://wiki.fluentnhibernate.org/Conventions) – James Gregory Nov 05 '10 at 13:13
0

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

James L
  • 16,456
  • 10
  • 53
  • 70