views:

32

answers:

1

When I use SchemaExport with SQL Server 2005, it generate unique key name like: UQ_Employees_03317E3D

Hom can I generate a name like: UQ_Employees_Name? Even in SQL Server!

+1  A: 

I think that there is a couple of ways to do what you are trying to to.

The first one is to specify the name in the mapping file. I know it works for foreign keys, though I haven't tried with unique keys.

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

Within NHibernate you can change the Naming Strategy by creating a class that implements NHibernate.Cfg.INamingStrategy and adding that class when you configure nhibernate.

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

The is also an ImprovedNamingStrategy that is built in to nhibernate. Can't remember what it outputs off hand but worth a try

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

EDIT
There are a couple of other possibilities I have found the first one involves the property tag. there is a column tag that has a number of attributes that may be of use.

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

the other one is a bit more involved You can either add something like this

<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>

Or create a class that implements NHibernate.Mapping.IAuxiliaryDatabaseObject which will create the DDL statements.
Have a look in the NHiberate manual on NHForge and scroll down to

5.6. Auxiliary Database Objects

This explains what you need to do.

Nathan Fisher
The first way can't work.Currently, the specified value of the unique-key is not used to name the constraint, only to group the columns in the mapping file.I'll try "NamingStrategy" way.
ldp615
And the "NamingStrategy" way can't work either.NHibernate.Cfg.INamingStrategy cares only about table names and column names.
ldp615
Sorry about about that. I will check to see if there is any other way to accomplish what you are after.
Nathan Fisher
Added more info to the answer.
Nathan Fisher