Search code examples
nhibernatenhibernate-mapping

Nhibernate: Map column that may not exist in database


Is there a way to map a column that may or may not exist in database or to map it dynamically to a column?


Solution

  • You can dynamically change the mappings but I don't think there is a way to map a column that may or may not exist. The below example is how you might do it if you were using fluent nhibernate.

    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)
    {
        //Check to see if there are any missing columns from this mapping.
        //If so remove the column from the mapping.
    
        //TODO: Query the database and catch errors related to missing columns
        //      If a column is missing remove it
    }
    
    var sessionFactory = config.BuildSessionFactory();