how can I map a dynamic table name to a entity? Ex, I can have many tables, all have the same structure, however, has its different name, how can I map this using Fluent NHibernate? remembering that before compiling I do not know the name of these tables. Can anyone help me?
Asked
Active
Viewed 1,704 times
2
-
It looks like you have a problem with your design in the first place - why do you need to have the same structure within different tables? Isn't it better to have a single table, but with a type field? – Archeg Aug 06 '13 at 14:59
-
I need because the quantity of tables are dinamicaly, and the location of this table too, in another DB or not. – Only a Curious Mind Aug 06 '13 at 16:54
-
I still would suggest you to try to review your design - usually even if you have different quantity of data - if it has the same structure you still can keep it in a single table. But if you really need dynamic mapping - you should aim the answer Cole has. – Archeg Aug 06 '13 at 20:18
1 Answers
0
What you'll probably need to do is put a place holder in the fluent nhibernate mapping for the table name and then replace it after you build the mappings.
Take a look at the following article and I think the first code sample will give you an idea of what you need to do.
http://ayende.com/blog/3294/dynamic-mapping-with-nhibernate
I was able to do this. Here is a rough example:
var fluentConfiguration = Fluently.Configure(NHibernate.Cfg.Configuration().Configure())
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<OrderMap>()
.Conventions.AddFromAssemblyOf<PascalCaseColumnNameConvention>())
.ProxyFactoryFactory("NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate");
var config = fluentConfiguration.BuildConfiguration();
foreach(PersistentClass persistentClass in config.ClassMappings)
{
if(persistentClass.MappedClass == typeof(Order))
{
persistentClass.Table.Name = "Dynamic Table";
}
}
//You could substitute above for each loop with linq unless you have a bunch to replace then use foreach
//config.ClassMappings.First(x => x.MappedClass == typeof(Order)).Table.Name = "Dynamic Table";
var sessionFactory = config.BuildSessionFactory();
using(ISession session = sessionFactory.OpenSession())
{
Order order = session.Query<Order>().FirstOrDefault();
}

Cole W
- 15,123
- 6
- 51
- 85