NHibernate SchemaExport: how to create a meaningful unique key name?

When I use SchemaExport with SQL Server 2005, it generates unique key names, for example:

UQ__Employees__03317E3D

How can I generate a name like: UQ__Employees__Name? Even in SQL Server!

+5
source share
3 answers

I think there are several ways to do what you are trying to do.

The first is to specify a name in the mapping file. I know this works for foreign keys, although I have not tried with unique keys.

<property name="KeyId" column="KeyId" type="Int" unique="true" unique-key="MyKeyName"/>

Inside NHibernate, you can change the naming strategy by creating a class that implements NHibernate.Cfg.INamingStrategyand adds this class when you configure nhibernate.

ISessionFactory sf = new Configuration()  
     .SetNamingStrategy(new YourNamingStrategy())  
     .Configure()  
     .SchemaExport(true, false);

ImprovedNamingStrategy, nhibernate. , , .

ISessionFactory sf = new Configuration()
    .SetNamingStrategy(ImprovedNamingStrategy.Instance)
    .Configure()
    .SchemaExport(true, false);


, . , , .

<property name=KeyID>
  <column name="KeyId" unique-key="MyKeyName"/>
</property>

- -

<database-object >
   <create>
      create table MyTable(
      Id UNIQUEIDENTIFIER not null,
      Name NVARCHAR(10) not null,
      RowVersion INT not null,

      primary key (Id)
      )

ALTER TABLE dbo.MyTable ADD  
  CONSTRAINT IX_Table_1 UNIQUE NONCLUSTERED(Name) 
  WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    </create>
    <drop></drop>
</database-object>

, NHibernate.Mapping.IAuxiliaryDatabaseObject, DDL.
NHiberate nhibernate.info

5,6.

, .

+3

(-) NHibernate. , 2.0 . NHibernate . , , . snippit , , , , .

+1

SchemaExport PK , :

DECLARE @PKname nvarchar(255), @TName nvarchar(255), @TName2 nvarchar(258) DECLARE PKCursor CURSOR FOR SELECT PK.name, T.name AS Tname FROM sys.sysobjects AS PK INNER JOIN sys.sysobjects AS T ON PK.parent_obj = T.id WHERE (PK.xtype = 'PK') OPEN PKCursor FETCH NEXT FROM PKCursor INTO @PKname, @TName WHILE @@FETCH_STATUS = 0 BEGIN SET @TName2 = 'PK_' + @TName PRINT 'table ' + @TName + ' : renaming ' + @PKname + ' in ' + @TName2 Exec sp_rename @PKname, @TName2, 'OBJECT' FETCH NEXT FROM PKCursor INTO @PKname, @TName END CLOSE PKCursor DEALLOCATE PKCursor

: http://www.primordialcode.com/blog/post/nhibernate-give-primary-key-schemaexport-sql-server-sql-express

0

All Articles