Search code examples
nhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mapping

Switching Database for the same mapped table


I use Fluent NHibernate and have to work with archived data right now, where the same table exists on multiple MSSQL Databases. Depending on a user provided Date value, I have to connect to a different Database, whereas all Mapping information remains the same.

More specific : if the provided Date value is within the current year, use DB CUR, otherwise use an annual DB (2011, 2010, 2009,...).

Now there was a time when people told me that re-creating a SessionFactory over and over is quite an expensive thing to do, so I thought to myself that there must be a way to use the existing sessionFactory, Update my ClassMap (something like change Schema from "CUR.DBO" to "2011.DBO") and reconnect.

I tried mess with both FluentConfiguration and SessionFactory, but then I took an arrow in the knee couldn't find a way to refresh the mappings at runtime.

Will I end up creating a new SessionFactory? Or does anyone out there know a viable procedure to reinitialize (Fluent) NHibernate's mappings at runtime?

EDIT: One very important detail, the SqlConnection is provided externally, too. It provides access to all databases, meaning that, in theory, I'll never have to create Connections. So, basically what I have to do is create a SessionFactory for each Archive to update the Mapping's Schema information, pointing to another database. But this is exactly where I'm stuck.


Solution

  • Thanks for your responses / comments. Actually I haven't found a way to reuse the session factory, so I ended up creating a lookup list for them as proposed. The following solution does what I need (change the database), we shall how it performs:

        private IDictionary<string, ISessionFactory> _sessionFactories;
    
        public SqlConnection Connection { get; set; }
    
        public ISessionFactory GetSessionFactory(string dbName)
        {
            if (_sessionFactories.ContainsKey(dbName))
            {
                return _sessionFactories[dbName];
            }
    
            FluentConfiguration cfg = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
                                                                    .ShowSql()
                                                                    .ConnectionString(c=>c.Is(Connection.ConnectionString)))
                                                          .Mappings(x=>x.FluentMappings.Add<MappedClassMap>());
            cfg.ExposeConfiguration(x => x.GetClassMapping(typeof(MappedClass)).Table.Schema = string.Format("{0}.dbo",dbName));
            ISessionFactory sf = cfg.BuildSessionFactory();
            _sessionFactories.Add(dbName, sf);
            return sf;
        }