Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure NHibernate (or Fluent NHib) to add a table name prefix to all table names?

In the current application I'm developing I'm using Fluent NHibernate to configure NHibernate for use as an ORM. I want to be able to add a prefix to all the table names used in the application, so that if I use a database that is already servicing another application, there are no naming conflicts between the two applications.

So for instance if I wanted to add a prefix of Portal_ to each table, the Users table would become Portal_Users.

Of course, I know how to configure each table name in each mapping file, but that's not really a good solution for what I'm trying to do. If I ever wanted to change the prefix, I would be forced to change each of the mapping files. I want to be able to add (or change) the prefix to all the table names in a single place in my code or configuration.

How does one add a prefix to all table names within an application using NHibernate (or Fluent NHibernate)?

like image 884
Mark Rogers Avatar asked Oct 05 '09 15:10

Mark Rogers


2 Answers

You can implement your own INamingStrategy and specify it for your Configuration:

Configuration config = new Configuration();
config.SetNamingStrategy(new MyTablePrefixStrategy());
like image 56
ChssPly76 Avatar answered Oct 21 '22 06:10

ChssPly76


For a fluent implementation..

 public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
    {
        public AutoPersistenceModel Generate()
        {
            var mappings = new AutoPersistenceModel();
            mappings.AddEntityAssembly(typeof(User).Assembly).Where(GetAutoMappingFilter);
            mappings.Conventions.Setup(GetConventions());

.....
    private Action<IConventionFinder> GetConventions()
    {
        return c =>
        {
            c.Add<PrimaryKeyConvention>();
            c.Add<ReferenceConvention>();
            c.Add<HasManyConvention>();
            c.Add<TableNameConvention>();

......

       public class TableNameConvention : IClassConvention
        {
            public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance 
instance)
            {
                instance.Table(Inflector.Net.Inflector.Pluralize("Portal_" + 
    instance.EntityType.Name));
                }
            }
like image 38
dove Avatar answered Oct 21 '22 07:10

dove