Do you use NH exporting schema?

Billy McCarfferty came in last week did a 3-day NH training for us. It was so great! I realize we’ve wasted so much time on those stupid things like SP, schema design, mapping test.

I added this code into our project after course.

   [TestFixture]
    public class MappingIntegrationTests
    {

        [SetUp]
        public void Setup()
        {
            NHibernateConfigure.InitializeNHibernateFactory<Organization>("Stakeholder");
        }

        [Test]
        public void CanConfirmDatabaseMatchesMappings()
        {

            IDictionary<string, IClassMetadata> allClassMetadata =
                NHibernateConfigure.GetSessionFactory().GetAllClassMetadata();

            using (ISession session = NHibernateConfigure.GetSessionFactory().OpenSession())
            {
                foreach (var entry in allClassMetadata)
                {
                    session.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco))
                        .SetMaxResults(0).List();
                }
            }
        }

        [Test]
        public void CanGenerateDatabaseSchema()
        {
            using (ISession session = NHibernateConfigure.GetSessionFactory().OpenSession())
            {
                using (TextWriter stringWriter =
                    new StreamWriter("UnitTestGeneratedSchema.sql"))
                {
                    new SchemaExport(NHibernateConfigure.GetConfiguration())
                        .Execute(true, false, false, session.Connection, stringWriter);
                }
            }
        }
    }

    public class NHibernateConfigure
    {
        private static ISessionFactory _sessionFactory;
        private static Configuration _configuration;

        public static ISessionFactory GetSessionFactory()
        {
            return _sessionFactory;
        }

        public static Configuration GetConfiguration()
        {
            return _configuration;
        }

        /// <summary>
        /// Initialize Fluent NHibernate without show-sql
        /// </summary>
        /// <typeparam name="T">A sample class in mapping assembly</typeparam>
        /// <param name="connectionStringKey"></param>
        public static void InitializeNHibernateFactory<T>(string connectionStringKey)
        {
            InitializeNHibernateFactory<T>(connectionStringKey, false);
        }

        ///<summary>
        /// Can accept show-sql flag, default is false.
        ///</summary>
        ///<param name="connectionStringKey"></param>
        ///<param name="showSql"></param>
        ///<typeparam name="T"></typeparam>
        ///<exception cref="System.Configuration.ConfigurationErrorsException"></exception>
        public static void InitializeNHibernateFactory<T>(string connectionStringKey, bool showSql)
        {
            ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[connectionStringKey];

            if (connectionString == null)
                throw new ConfigurationErrorsException(connectionStringKey +
                                                       " connection string key does not exist in config file.");

            MsSqlConfiguration sqlConfiguration = MsSqlConfiguration.MsSql2005
                .ConnectionString(x => x.FromConnectionStringWithKey(connectionStringKey));

            if (showSql) sqlConfiguration = sqlConfiguration.ShowSql();

            FluentConfiguration config = Fluently.Configure()
                .Database(
                    sqlConfiguration
                        .Raw("hibernate.generate_statistics", "true")
                        .ProxyFactoryFactory(
                            "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<T>()
                                   .ExportTo(Path.GetTempPath())
                )
                .ExposeConfiguration((c => c.SetProperty("generate_statistics", "true")))
                ;

            _configuration = config.BuildConfiguration();
            _sessionFactory = config.BuildSessionFactory();

            NHibernateFactory.Initialize(_sessionFactory);
            return;
        }
    }

The schema generated by NH looks very pretty, but our DBA doesn’t trust it and refuse to use it.

Do you use NH exporting schema?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s