Question

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?

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top