Wednesday 8 February 2012

Fluent NHibernate PK Rename convention (SQL Server)

Following on from my previous post of using some sql to enable the SchemaExport tool to make changes outside of its current capabilities, I created a simple convention for Fluent NHibernate which enables you to name the PK’s of tables.
Currently this only works with SQL Server, but I believe that this approach should also be possible in other databases.
using System.Linq;
using System.Text;
using Iesi.Collections.Generic;
using NHibernate.Dialect;
using NHibernate.Mapping;

namespace Conventions
{
    public class CustomPrimaryKeyIndexNameConvention
    {
        public static void CreateUpdatePkNameScript(NHibernate.Cfg.Configuration config)
        {
            var script = new StringBuilder("");
            script.AppendLine("DECLARE @keyName AS SYSNAME");
            script.AppendLine();
            foreach (var tableName in config.ClassMappings.Select(m => m.Table.Name).Distinct())
            {
                script.AppendFormat(string.Format("SELECT  @keyName = name FROM sys.key_constraints kc WHERE kc.parent_object_id = OBJECT_ID('dbo.{0}', 'U')", tableName));
                script.AppendLine();
                script.AppendFormat("EXEC sp_rename @keyName, N'PK_{0}', N'OBJECT';", tableName);
                script.AppendLine();
            }

            config.AddAuxiliaryDatabaseObject(new SimpleAuxiliaryDatabaseObject(script.ToString(), null, new HashedSet<string> { typeof(MsSql2000Dialect).FullName, typeof(MsSql2005Dialect).FullName, typeof(MsSql2008Dialect).FullName }));
        }
    }
}
As you can see, the convention is to use “PK_<TableName>” for the PK name and is applied using the Auxiliary database extensions:
.ExposeConfiguration(CustomPrimaryKeyIndexNameConvention.CreateUpdatePkNameScript)

Submit this story to DotNetKicks Shout it

No comments:

Post a Comment