Changing the default naming convention for foriegn keys when using Fluent NHibernate

By default, NHibernate will assume that foreign keys should be named using the convention ReferencedTableName_id (e.g. Person_id). I personally don’t like this conversion and would prefer ReferencedTableNameId (e.g. PersonId).

Fortunately, this is pretty easy to achieve by extending the ForeignKeyConvention class in Fluent NHibernate:

using System;
using FluentNHibernate;
using FluentNHibernate.Conventions;

namespace NHibernate.Helpers.Conventions
    public class CustomForeignKeyConvention : ForeignKeyConvention
        protected override string GetKeyName(Member property, System.Type type)
            if (property != null)
                return property.Name + "Id";

            if (type != null)
                return type.Name + "Id";

            // If both are null, we throw an exception:
            throw new ArgumentNullException("property", "The property and type parameters cannot both be null");

This needs to be wired into your SessionFactory creation code as follows:

sessionFactory = Fluently.Configure()
    .Mappings(x => x.FluentMappings.AddFromAssembly(MappingsAssembly))
    .Mappings(x => x.FluentMappings.Conventions.Add(new CustomForeignKeyConvention()))
    .ExposeConfiguration(x => new SchemaUpdate(x).Execute(false, true))

Note that the example above will also update the database schema.

Once you’ve done that, all foreign keys will use the desired naming convention.

Leave a Reply

Your email address will not be published. Required fields are marked *