Currently I have two databases of identical structure (one is for temp changes, another is live one). I use same NHibernate entities, mappings and repositories to access both databases. Only connection string is changed when creating Session.
Now I need to change approach and merge those two DBs into one. I'm planning to separate equally named tables by introducing different schemas for them. Sounds easy. But the problem arised when I checked how to update my NHibernate mappings so that they support either one schema or another - it seems that map classes support only parameterless constructors (at least all methods to add mappings to NHibernate configuration doesn't suppose any constructor parameters).
Here is some sample code to demonstrate what I'd like to achieve:
public class MyEntityMap : ClassMap<MyEntity>
{
public MyEntityMap ()
{
Table("MyEntities");
Schema("a"); //I can specify schema as a constant here, but I need it to be variable: constructor either parameter or changable in other way
Id(x => x.Id, "Id");
Map(x => x.Name, "Name").Length(100);
}
}
When creating NHibernate configuration there are the following options to add mappings to it (three method calls are shown just for options, I use single call to AddFromAssemblyOf currently):
Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString("MyConnectionString"))
.Mappings(m => m.FluentMappings.AddFromAssembly(typeof (MyEntityMap).Assembly))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyEntityMap>())
.Mappings(m => m.FluentMappings.Add<MyEntityMap>)
Obviously neither option supports parameterized constructor of ClassMap derived classes and I can't see how else can I specify schema for all mappings at once.
Solutions I see (but which seem to be an overkill):
- Manually create 2 derived classes from each mapping class and place them in different assemblies. So that each class provide it's value for schema constant.
- Autogenerate 2 mapping classes, derived from each 'base' mapping using
System.Emit. Use assemblies, generated at runtime to pass toAddMappingFromAssemblymethod.
Am I missing something? Is there an easy way to specify which schema to use for all repositories, created using specified NHibernate configuration?
MsSql2008Configuration: looks as a custom class specific to your code. I guess it does inherit fromNHibernate.Cfg.Configuration, doesn't it? - Frédéric