public void CanSetDefaultFlushModeThroughLoquaciousConfiguration()
		{
			var cfg = new Configuration()
				.Configure();

			cfg
				.SessionFactory()
				.DefaultFlushMode(FlushMode.Always);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				using (var session = sessionFactory.OpenSession())
				{
					Assert.AreEqual(FlushMode.Always, session.FlushMode);
				}
			}

			cfg.Configure()
				.SessionFactory()
				.DefaultFlushMode(FlushMode.Commit);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				using (var session = sessionFactory.OpenSession())
				{
					Assert.AreEqual(FlushMode.Commit, session.FlushMode);
				}
			}
		}
        public void PrepareSessionFactory()
        {
            Configuration = new Configuration();
            Configuration.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>())
                .DataBaseIntegration(db =>
                                         {
                                             db.ConnectionStringName = "db";
                                             db.Dialect<MsSql2008Dialect>();
                                         });
            Configuration.SetProperty("show_sql", "true");
            Configuration.SetDefaultAssembly("NHibernateDeepDive");
            Configuration.SetDefaultNamespace("NHibernate_Deep_Dive.Entities");
            Configuration.AddXmlFile("ClearDatabaseScript.hbm.xml");
            foreach (var mappingFile in Directory.GetFiles(MappingsDirectory))
            {
                Configuration.AddXmlFile(mappingFile);
            }
            AdjustConfiguration(Configuration);
            Configuration.SessionFactory().GenerateStatistics();

            SessionFactory = Configuration.BuildSessionFactory();

            //new SchemaExport(Configuration).Drop(false, true);
            new SchemaExport(Configuration).Execute(false, true, false);

            BeforeTestRun();
            PopulateDatabase();

            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }
        private ISessionFactory BuildSessionFactory()
        {
            var mapper = new ModelMapper();
            var configuration = new Configuration();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            configuration.DataBaseIntegration(c =>
            {
                c.ConnectionString = _connectionString;
                c.IsolationLevel = IsolationLevel.ReadCommitted;
                c.Driver<Sql2008ClientDriver>();
                c.Dialect<MsSql2008Dialect>();
                c.BatchSize = 50;
                c.Timeout = 30;

            #if DEBUG
                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;
                c.AutoCommentSql = true;
            #endif
            });

            #if DEBUG
            configuration.SessionFactory().GenerateStatistics();
            #endif

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            var sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory;
        }
 public void TestFixtureSetUp()
 {
     configuration = new Configuration();
     configuration.SessionFactory()
                  .Integrate.Using<SQLiteDialect>()
                  .Connected.Using("Data source=testdb")
                  .AutoQuoteKeywords()
                  .LogSqlInConsole()
                  .EnableLogFormattedSql();
     var mapper = new ConventionModelMapper();
     mapper.Class<Foo>(cm => { });
     mapper.Class<Bar>(cm => { });
     CustomizeMapping(mapper);
     var mappingDocument = mapper.CompileMappingForAllExplicitlyAddedEntities();
     new XmlSerializer(typeof(HbmMapping)).Serialize(Console.Out, mappingDocument);
     configuration.AddDeserializedMapping(mappingDocument, "Mappings");
     new SchemaExport(configuration).Create(true, true);
     sessionFactory = configuration.BuildSessionFactory();
     using (var session = sessionFactory.OpenSession())
     using (var tx = session.BeginTransaction())
     {
         var foo = new Foo { Bars = CreateCollection() };
         foo.Bars.Add(new Bar { Data = 1 });
         foo.Bars.Add(new Bar { Data = 2 });
         id = session.Save(foo);
         tx.Commit();
     }
     sessionFactory.Statistics.IsStatisticsEnabled = true;
 }
 static OracleSessionFactoryHelper()
 {
     var cfg = new Configuration();
     cfg.SessionFactory()
            .Proxy
                .DisableValidation()
                .Through<NHibernate.Bytecode.DefaultProxyFactoryFactory>()
                .Named("Fluent.SessionFactory")
                .GenerateStatistics()
                .Using(EntityMode.Poco)
                .ParsingHqlThrough<NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory>()
            .Integrate
                .Using<Oracle10gDialect>()
                .AutoQuoteKeywords()
                .LogSqlInConsole()
                .EnableLogFormattedSql()
            .Connected
                .Through<DriverConnectionProvider>()
                .By<OracleDataClientDriver>()
                .ByAppConfing("ConnectionString")
            .CreateCommands
                .Preparing()
                .WithTimeout(10)
                .AutoCommentingSql()
                .WithMaximumDepthOfOuterJoinFetching(11)
                .WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'");
     SessionFactory = FluentNHibernate.Cfg.Fluently.Configure(cfg)
            .Database(OracleDataClientConfiguration.Oracle10.ShowSql())
            .Mappings(m => GetMappingsAssemblies().ToList()
                .ForEach(o => m.FluentMappings.AddFromAssembly(o))).BuildSessionFactory();
 }
        private Configuration CreateConfiguration(IKernel kernel)
        {
            var config = new Configuration()
                .Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>());
#if DEBUG
            config.SessionFactory().GenerateStatistics();
#endif      
            return config;
        }
Beispiel #7
0
 public static ISessionFactory GetSessionFactory()
 {
     var config = new Configuration();
     config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using("Data source=nhtest.sqlite").AutoQuoteKeywords();
     var mapper = new ConventionModelMapper();
     Map(mapper);
     config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "Mappings");
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
     new SchemaUpdate(config).Execute(false, true);
     return config.BuildSessionFactory();
 }
Beispiel #8
0
 public static ISessionFactory GetSessionFactory()
 {
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
     var config = new Configuration();
     //config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using("Data source=nhtest.sqlite").AutoQuoteKeywords();
     config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using(String.Format("Data source={0}", Path.Combine(clientPath, "nhtest.sqlite"))).AutoQuoteKeywords();
     var mapper = new ConventionModelMapper();
     Map(mapper);
     config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "Mappings");
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
     new SchemaUpdate(config).Execute(false, true);
     return config.BuildSessionFactory();
 }
Beispiel #9
0
        private static Configuration Configure(Configuration self, string connectionString)
        {
            self.DataBaseIntegration(db =>
                                         {
                                             db.ConnectionString = connectionString;
                                             db.Driver<SQLite20Driver>();
                                             db.Dialect<SQLiteDialect>();
                                             db.LogFormattedSql = true;
                                             db.LogSqlInConsole = true;
                                             db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                                             db.SchemaAction = SchemaAutoAction.Recreate;
                                         });

            self.SessionFactory().GenerateStatistics();

            return self;
        }
 public void TestFixtureSetUp()
 {
     var configuration = new Configuration();
     configuration.SessionFactory()
                  .Integrate.Using<SQLiteDialect>()
                  .Connected.Using("Data source=testdb")
                  .AutoQuoteKeywords()
                  .LogSqlInConsole()
                  .EnableLogFormattedSql();
     var mapper = new ConventionModelMapper();
     MapClasses(mapper);
     var mappingDocument = mapper.CompileMappingForAllExplicitlyAddedEntities();
     new XmlSerializer(typeof(HbmMapping)).Serialize(Console.Out, mappingDocument);
     configuration.AddDeserializedMapping(mappingDocument, "Mappings");
     new SchemaExport(configuration).Create(true, true);
     sessionFactory = configuration.BuildSessionFactory();
 }
Beispiel #11
0
 public DatabaseFactory(ILoadBalanceScheduling loadBalanceScheduling)
 {
     //根据DbSnapInfo快照连接,创建ISessionFactory
     DbSnapInfo dbSnapInfo = loadBalanceScheduling.GetConnectDbSnap();
     Configuration cfg = new Configuration();
     cfg.SessionFactory().Integrate.Using<MsSql2008Dialect>().Connected.Using(dbSnapInfo.DbconnectString);
     //设置Mapping默认程序集 
     cfg.AddAssembly("Infrastructure.Data.MainBoundedContext");
     //设置proxyfactory
     cfg.SetProperty("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
     //设置缓存程序
     cfg.SetProperty("cache.provider_class", "NHibernate.Cache.HashtableCacheProvider");
     //启动二级缓存
     cfg.SetProperty("cache.use_second_level_cache", "true");
     //启动查询缓存
     cfg.SetProperty("cache.use_query_cache", "true");
     sessionFactory = cfg.BuildSessionFactory();
 }
        public static ISessionFactory BuildSessionFactory()
        {
            Configuration cfg = new Configuration();
            cfg.SessionFactory()
                .Integrate.Using<MsSql2008Dialect>()
                .Connected.Using(new SqlConnectionStringBuilder {
                        DataSource = @".\SQLEXPRESS",
                        InitialCatalog = "aspnet-webapi",
                        IntegratedSecurity = true
                    })
                .Schema.Updating();
            var mapper = new ModelMapper();
            mapper.AddMappings(typeof(ProductMap).Assembly.GetTypes()
                                                          .Where(t => t.Namespace != null && t.Namespace.StartsWith("webapi.Infrastructure.Mappings")));
            HbmMapping mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mappings);
            return cfg.BuildSessionFactory();
        }
        public void Should_work_with_nhibernate()
        {
            Configuration configuration = new Configuration();
            configuration.SessionFactory()
                .Integrate.Using<SQLiteDialect>()
                .Connected.Using(new SQLiteConnectionStringBuilder{DataSource = ":memory:", Version = 3}).LogSqlInConsole();
            configuration.AddDeserializedMapping(DomainMapper.GetMappings(), "domain");

            using(var factory = configuration.BuildSessionFactory())
            {
                using(var session = factory.OpenSession())
                {
                    new SchemaExport(configuration).Execute(true, true, false, session.Connection, Console.Out);
                    ProductsCalculator productsCalculator = new ProductsCalculator(new Repository<Product>(session));
                    var price = productsCalculator.GetTotalPrice();

                    Assert.That(price, Is.EqualTo(0));
                }
            }
        }
        static void Main()
        {
            NHibernateProfiler.Initialize();

            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
                                        {
                                            x.ConnectionStringName = "scratch";
                                            x.Driver<SqlClientDriver>();
                                            x.Dialect<MsSql2008Dialect>();
                                        });
            cfg.SessionFactory().GenerateStatistics();
            cfg.AddAssembly(typeof (Program).Assembly);

            var exporter = new SchemaExport(cfg);
            exporter.Execute(false, true, false);

            var sessionFactory = cfg.BuildSessionFactory();
            using(var session = sessionFactory.OpenSession())
            using(var tx = session.BeginTransaction())
            {
                var module = new Module { ModuleCode = new ModuleCode { Value = "class Foo; end;" } };
                session.Save(module);
                tx.Commit();
            }
            using(var session = sessionFactory.OpenSession())
            using(var tx = session.BeginTransaction())
            {
                var module = session.QueryOver<Module>().List().First();
                Console.WriteLine(module.ModuleXml);
            //                Console.WriteLine(module.ModuleCode);
            //                Console.WriteLine(module.ModuleXml);
                tx.Commit();
            }
            Console.WriteLine("Press <ENTER> to exit...");
            Console.ReadLine();
        }
Beispiel #15
0
        private static FluentConfiguration CreateNHibernateConfiguration()
        {
            var nhibernateConfiguration = new Configuration().Cache(x => x.UseQueryCache = true);

            nhibernateConfiguration.SessionFactory().Caching.Through <SysCacheProvider>().WithDefaultExpiration(60);

            FluentConfiguration configuration = Fluently.Configure(nhibernateConfiguration)
                                                .Database(
                MsSqlConfiguration.MsSql2012.ConnectionString(
                    ConfigurationManager.ConnectionStrings["CatalogOnlineConnectionString"]
                    .ConnectionString)
                .ShowSql())
                                                .CurrentSessionContext("thread_static")
                                                .Mappings(m => m.FluentMappings
                                                          .AddFromAssemblyOf <UserMap>()
                                                          .AddFromAssemblyOf <UserAddressMap>()
                                                          .AddFromAssemblyOf <ProductCategoryMap>()
                                                          .AddFromAssemblyOf <ProductMap>()
                                                          .AddFromAssemblyOf <ShopMap>()
                                                          .AddFromAssemblyOf <BasketMap>()
                                                          .AddFromAssemblyOf <OrderMap>());

            return(configuration);
        }
		public void CompleteConfiguration()
		{
			// Here I'm configuring near all properties outside the scope of Configuration class
			// Using the Configuration class the user can add mappings and configure listeners
			var cfg = new Configuration();
			cfg.SessionFactory().Named("SomeName")
				.Caching
					.Through<HashtableCacheProvider>()
					.PrefixingRegionsWith("xyz")
					.Queries
						.Through<StandardQueryCache>()
					.UsingMinimalPuts()
					.WithDefaultExpiration(15)
				.GeneratingCollections
					.Through<DefaultCollectionTypeFactory>()
				.Proxy
					.DisableValidation()
					.Through<ProxyFactoryFactory>()
				.ParsingHqlThrough<ClassicQueryTranslatorFactory>()
				.Mapping
					.UsingDefaultCatalog("MyCatalog")
					.UsingDefaultSchema("MySche")
				.Integrate
					.Using<MsSql2000Dialect>()
					.AutoQuoteKeywords()
					.BatchingQueries
						.Through<SqlClientBatchingBatcherFactory>()
						.Each(15)
					.Connected
						.Through<DebugConnectionProvider>()
						.By<SqlClientDriver>()
						.Releasing(ConnectionReleaseMode.AfterTransaction)
						.With(IsolationLevel.ReadCommitted)
						.Using("The connection string")
					.CreateCommands
						.AutoCommentingSql()
						.ConvertingExceptionsThrough<SQLStateConverter>()
						.Preparing()
						.WithTimeout(10)
						.WithMaximumDepthOfOuterJoinFetching(11)
						.WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'")
					.Schema
						.Validating()
			;

			Assert.That(cfg.Properties[Environment.SessionFactoryName], Is.EqualTo("SomeName"));
			Assert.That(cfg.Properties[Environment.CacheProvider],
									Is.EqualTo(typeof(HashtableCacheProvider).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.CacheRegionPrefix], Is.EqualTo("xyz"));
			Assert.That(cfg.Properties[Environment.QueryCacheFactory],
									Is.EqualTo(typeof(StandardQueryCache).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.UseMinimalPuts], Is.EqualTo("true"));
			Assert.That(cfg.Properties[Environment.CacheDefaultExpiration], Is.EqualTo("15"));
			Assert.That(cfg.Properties[Environment.CollectionTypeFactoryClass],
									Is.EqualTo(typeof(DefaultCollectionTypeFactory).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.UseProxyValidator], Is.EqualTo("false"));
			Assert.That(cfg.Properties[Environment.ProxyFactoryFactoryClass],
						Is.EqualTo(typeof(ProxyFactoryFactory).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.QueryTranslator],
						Is.EqualTo(typeof(ClassicQueryTranslatorFactory).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.DefaultCatalog], Is.EqualTo("MyCatalog"));
			Assert.That(cfg.Properties[Environment.DefaultSchema], Is.EqualTo("MySche"));
			Assert.That(cfg.Properties[Environment.Dialect],
						Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote"));
			Assert.That(cfg.Properties[Environment.BatchStrategy],
						Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.BatchSize], Is.EqualTo("15"));
			Assert.That(cfg.Properties[Environment.ConnectionProvider],
						Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.ConnectionDriver],
						Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.ReleaseConnections],
			            Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction)));
			Assert.That(cfg.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted"));
			Assert.That(cfg.Properties[Environment.ConnectionString], Is.EqualTo("The connection string"));
			Assert.That(cfg.Properties[Environment.UseSqlComments], Is.EqualTo("true"));
			Assert.That(cfg.Properties[Environment.SqlExceptionConverter],
									Is.EqualTo(typeof(SQLStateConverter).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.PrepareSql], Is.EqualTo("true"));
			Assert.That(cfg.Properties[Environment.CommandTimeout], Is.EqualTo("10"));
			Assert.That(cfg.Properties[Environment.MaxFetchDepth], Is.EqualTo("11"));
			Assert.That(cfg.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'"));
			Assert.That(cfg.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate"));
		}
		public void UseConnectionStringName()
		{
			var cfg = new Configuration();
			cfg.SessionFactory()
				.Integrate
					.Connected
						.ByAppConfing("MyName");

			Assert.That(cfg.Properties[Environment.ConnectionStringName], Is.EqualTo("MyName"));
		}
		public void UseDbConfigurationStringBuilder()
		{
			// This is a possible minimal configuration
			// in this case we must define best default properties for each dialect
			// The place where put default properties values is the Dialect itself.
			var cfg = new Configuration();
			cfg.SessionFactory()
				.Proxy.Through<ProxyFactoryFactory>()
				.Integrate
					.Using<MsSql2005Dialect>()
					.Connected
						.Using(new SqlConnectionStringBuilder
						       	{
						       		DataSource = "(local)", 
											InitialCatalog = "nhibernate", 
											IntegratedSecurity = true
						       	});

			Assert.That(cfg.Properties[Environment.ProxyFactoryFactoryClass],
			            Is.EqualTo(typeof (ProxyFactoryFactory).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.Dialect],
									Is.EqualTo(typeof(MsSql2005Dialect).AssemblyQualifiedName));
			Assert.That(cfg.Properties[Environment.ConnectionString],
									Is.EqualTo("Data Source=(local);Initial Catalog=nhibernate;Integrated Security=True"));
		}
Beispiel #19
0
        private void ConfigureNHibernate()
        {
            _configuration = new Configuration();
            _configuration.DataBaseIntegration(x =>
                {
                    if (_inMemory)
                    {
                        x.Dialect<SQLiteDialect>();
                        x.Driver<SQLite20Driver>();
                        x.ConnectionProvider<DriverConnectionProvider>();
                    }
                    else
                        x.Dialect<MsSql2008Dialect>();
                    x.ConnectionString = _connectionString;
                    x.SchemaAction = SchemaAutoAction.Update;
                    x.IsolationLevel = IsolationLevel.ReadCommitted;

                    x.HqlToSqlSubstitutions = "True 1, False 0, true 1, false 0, yes 'Y', no 'N'";
                    x.BatchSize = 200;
                });

            var mappingAssemblies = _assemblies;
            foreach (var mappingAssembly in mappingAssemblies.Where(mappingAssembly => !String.IsNullOrWhiteSpace(mappingAssembly)))
            {
                _configuration.AddAssembly(mappingAssembly);
            }
            _configuration.BuildMappings();
            _configuration.SetProperty(NHEnvironment.CacheDefaultExpiration, 120.ToString());
            _configuration.SetProperty(NHEnvironment.ShowSql, "false");
            _configuration.Proxy(cfg => cfg.ProxyFactoryFactory<DefaultProxyFactoryFactory>());
            _configuration.SessionFactory()
                          .GenerateStatistics();
        }
Beispiel #20
0
 protected override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     base.Configure(configuration);
     configuration.SessionFactory().Integrate.CreateCommands.WithHqlToSqlSubstitutions("pizza 1, calda 'bobrock'");
 }
Beispiel #21
0
        /// <summary>
        /// Configure NHibernate
        /// </summary>
        private void ConfigureNHibernate()
        {
            _configuration = new NHConfiguration();
            _configuration.DataBaseIntegration(x =>
                    {
                        //x.AutoCommentSql = true;
                        //x.Dialect<MsSqlCustomDialect>();
                        x.Dialect<MsSqlCustomDialect>();
                        x.ConnectionString = _connectionString;
                        x.SchemaAction = SchemaAutoAction.Update;
                        x.IsolationLevel = IsolationLevel.ReadCommitted;

                        x.HqlToSqlSubstitutions = "True 1, False 0, true 1, false 0, yes 'Y', no 'N'";
                        x.BatchSize = 15;
                    });

            var mappingAssemblies = _assemblies;
            foreach (var mappingAssembly in mappingAssemblies)
            {
                if (!String.IsNullOrWhiteSpace(mappingAssembly))
                {
                    _configuration.AddAssembly(mappingAssembly);
                }
            }

            _configuration.BuildMappings();
            _configuration.Cache(cfg =>
                                     {
                                         cfg.DefaultExpiration = 120;
                                         cfg.Provider<SysCacheProvider>();
                                         cfg.UseMinimalPuts = true;
                                         cfg.RegionsPrefix = "xyz";
                                         cfg.UseQueryCache = true;
                                     });
            _configuration.SetProperty(NHibernate.Cfg.Environment.CacheDefaultExpiration, 120.ToString());
            _configuration.SetProperty(NHibernate.Cfg.Environment.ShowSql, "false");
            _configuration.Proxy(cfg => cfg.ProxyFactoryFactory<DefaultProxyFactoryFactory>());
            _configuration.SessionFactory()
                          .GenerateStatistics();

            new AuditingEventListener().Register(_configuration);
        }
Beispiel #22
0
        public static ISessionFactory GetSessionFactory(string connectionKey, params Assembly[] assemblies)
        {
            var cfg  = new NHibernate.Cfg.Configuration();
            var sett = Alma.Common.Config.Settings;
            var conn = sett.GetConnectionString(connectionKey);

            switch (conn.Provider)
            {
            case DBMS.MsSql:

                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.MsSql2008Dialect>();
                    //db.Driver<DriverSqlClient>();
                    db.Driver <NHibernate.Driver.SqlClientDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;

                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });

                break;

            case DBMS.SqLite:
                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.SQLiteDialect>();
                    //db.Driver<DriverSQLite20>();
                    db.Driver <NHibernate.Driver.SQLite20Driver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });
                break;

            case DBMS.Oracle:
                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.Oracle10gDialect>();
                    if (true /* isManagedOracle */)
                    {
                        db.Driver <NHibernate.Driver.OracleManagedDataClientDriver>();
                    }
                    //else
                    //    db.Driver<NHibernate.Driver.OracleDataClientDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    db.Batcher <OracleLoggingBatchingBatcherFactory>();
                    //UseReflectionOptimizer
                });
                break;

            case DBMS.MySql:

                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                    //db.Driver<DriverMySql>();
                    db.Driver <NHibernate.Driver.MySqlDataDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });

                break;

            default:
                throw new NotImplementedException("Not implemented provider: " + conn.Provider);
            }

            if (sett.Logging.Enable)
            {
                cfg.SessionFactory()
                .GenerateStatistics();
            }

            var types =
                assemblies.SelectMany(a => a.GetTypes());

            AddFilters(cfg, types);

            AddEvents(cfg, types);

            AddMappings(cfg, types);

            try
            {
                var fact = cfg.BuildSessionFactory();
                return(fact);
            }
            catch (HibernateException ex)
            {
                if (ex.Message.Contains("NHibernate.Driver") && (conn.Provider == DBMS.Oracle))
                {
                    throw new System.Configuration.ConfigurationErrorsException(
                              @"Cannot find Oracle.DataAcces or Oracle.ManagedDataAccess binaries in GAC or working directory. 

Minimum Unmanaged Version: Oracle Client 11.2 with ODP.NET if using Full Framework 4.0/4.5. 
Remove all installed versions and install the required version and try again.", ex);
                }
                else
                {
                    throw;
                }
            }
        }
        //        public class Order
        //        {
        //            public int Id { get; set; }
        //            public Customer Customer { get; set; }
        //        }
        static void InitializeNHibernate()
        {
            NHibernateProfiler.Initialize();

            cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
                                        {
                                            x.ConnectionStringName = "adventureworks";
                                            x.Driver<SqlClientDriver>();
                                            x.Dialect<MsSql2008Dialect>();
                                            x.IsolationLevel = IsolationLevel.ReadCommitted;
                                            x.Timeout = 10;
                                        });
            cfg.SessionFactoryName("AdventureWorks");
            cfg.Cache(x =>
                          {
                              x.Provider<HashtableCacheProvider>();
                              x.UseQueryCache = true;
                          });
            cfg.SessionFactory().GenerateStatistics();
            cfg.AddAssembly(typeof (Customer).Assembly);
        }