コード例 #1
0
        public void ShouldVerifySameTableTurkish()
        {
            //NH-3063

            // Turkish have unusual casing rules for the letter 'i'. This test verifies that
            // code paths executed by the SchemaValidator correctly handles case insensitive
            // comparisons for this.

            // Just make sure that we have an int property in the mapped class. This is
            // the 'i' we rely on for the test.
            var v = new Version();

            Assert.That(v.Id, Is.TypeOf <int>());

            var cfg = BuildConfiguration(_version1Resource);

            var export = new SchemaExport(cfg);

            export.Create(true, true);
            try
            {
                var validator = new Tool.hbm2ddl.SchemaValidator(cfg);
                validator.Validate();
            }
            finally
            {
                export.Drop(true, true);
            }
        }
コード例 #2
0
        protected void RecreateDatabase()
        {
            var exporter = new SchemaExport(this.NhConfiguration);

            exporter.Drop(false, true);
            exporter.Create(false, true);
        }
コード例 #3
0
        public void Script()
        {
            var automapper = new AutoMapper
            {
                EntityBaseType = typeof(AutoMapperTestEntityBase)
            };

            automapper.MapAssemblyOf <SchemaTests>();

            var compiled = automapper.Complete();

            var configuration = new Configuration();

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <SQLiteDialect>();
                db.ConnectionString = "Data Source=:memory:;Version=3;New=True";
            });

            configuration.AddDeserializedMapping(compiled.First(), string.Empty);

            var export = new SchemaExport(configuration);

            export.Execute(true, false, false);
        }
コード例 #4
0
        public static void Initial(Configuration config, ILoggerFactory loggerFactory)
        {
            //config = config.Configure();
            config.Interceptor = new SQLWatcher(loggerFactory);
            //Enable validation(optional)
            NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true;
            //Here, we serialize all decorated classes(but you can also do it class by class)
            config.Properties["connection.driver_class"]      = "NHibernate.Driver.MySqlDataDriver";
            config.Properties["connection.connection_string"] = "Database = oa; Data Source = localhost; User Id = root; Password = wjp930514.; Old Guids = True; charset = utf8;";
            config.Properties["dialect"]                     = "NHibernate.Dialect.MySQL5Dialect";
            config.Properties["use_sql_comments"]            = "true";
            config.Properties["command_timeout"]             = "30";
            config.Properties["adonet.batch_size"]           = "100";
            config.Properties["order_inserts"]               = "true";
            config.Properties["order_updates"]               = "true";
            config.Properties["adonet.batch_versioned_data"] = "true";
            config.Properties["show_sql"]                    = "true";
            config.Properties["format_sql"]                  = "true";
            config.Properties["hbm2ddl.auto"]                = "update";
            config.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(Assembly.Load("OA.Domain")));
            //HbmSerializer.Default.Serialize(Assembly.Load("OA.Domain"), "Config/hibernate-oa.cfg.xml");
            //config.AddXmlFile("Config/hibernate-oa.cfg.xml");
            config.SessionFactory().GenerateStatistics();
            //用NHibernate.Tool.hbm2ddl.SchemaExport生成表结构到\sql.sql文件当中
            SchemaExport export = new SchemaExport(config);

            export.SetOutputFile(Path.Combine(Directory.GetCurrentDirectory(), "sql.sql")); //设置输出目录
                                                                                            // export.Drop(true, true);//设置生成表结构存在性判断,并删除
            export.Create(false, false);                                                    //设置是否生成脚本,是否导出来
        }
コード例 #5
0
        public void CreateDataBase()
        {
            var Schema = new SchemaExport(UnitOfWork.GetConfiguration());

            Schema.Drop(true, true);
            Schema.Create(true, true);
        }
コード例 #6
0
        public void Configure()
        {
            if (cfg == null)
            {
                cfg = new Configuration();
                var nhConfig = cfg.Proxy(proxy =>
                                         proxy.ProxyFactoryFactory <ProxyFactoryFactory>())
                               .DataBaseIntegration(db =>
                {
                    db.Dialect <MsSql2008Dialect>();
                    db.ConnectionStringName = "db";
                    db.BatchSize            = 100;
                }
                                                    );


                var mapper = new ModelMapper();
                mapper.AddMappings(coreType.Assembly.GetExportedTypes());
                HbmMapping domainMapping =
                    mapper.CompileMappingForAllExplicitlyAddedEntities();
                cfg.AddMapping(domainMapping);
                cfg.CurrentSessionContext <NHibernate.Context.ThreadStaticSessionContext>();

                sessionFactory = cfg.BuildSessionFactory();
                se             = new SchemaExport(cfg);
            }
        }
コード例 #7
0
        public void TestInitizlize()
        {
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
            {
                db.Dialect <SQLiteDialect>();
                db.Driver <SQLite20Driver>();
                db.ConnectionString = ConnectionString;
                db.LogSqlInConsole  = false;
                db.LogFormattedSql  = true;
                db.AutoCommentSql   = true;
            }
                );
            config.SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var mapper = new ModelMapper();

            mapper.WithMappings(config);

            ContextSessionFactory = config.BuildSessionFactory();

            ContextSession = ContextSessionFactory.OpenSession();

            var schemaExport = new SchemaExport(config);

            schemaExport.Execute(false, true, false, ContextSession.Connection, TextWriter.Null);

            Context();
            BecauseOf();
        }
コード例 #8
0
        private static void BuildSchema(Configuration configuration)
        {
            var schemaExport = new SchemaExport(configuration);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
コード例 #9
0
        public void ReCreateDbSchema()
        {
            var schemaExport = new SchemaExport(configuration);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
コード例 #10
0
        protected static void ResetDB()
        {
            Configuration config       = GetNHibernateConfig();
            var           schemaExport = new SchemaExport(config);

            schemaExport.Execute(true, true, false);
        }
コード例 #11
0
        public static ISessionFactory GetSessionFactory(SqlConnect sqlConnectProvider)
        {
            ISessionFactory factory = null;

            if (_cacheSessionFactory.TryGetValue(sqlConnectProvider.Name, out factory))
            {
                return(factory);
            }
            lock (_lockObj) {
                if (_cacheSessionFactory.TryGetValue(sqlConnectProvider.Name, out factory))
                {
                    return(factory);
                }
                FluentConfiguration config = Fluently.Configure();
                SetDefaultConfig(config);
                // if (conn.ProviderName.IndexOf("System.Data.SqlClient", StringComparison.OrdinalIgnoreCase) > -1)
                BuildMsSqlDatabase(config, sqlConnectProvider.ConnectionString);
                config.ExposeConfiguration(cfg =>
                {
                    cfg.SetProperty("command_timeout", "120");
                    var export = new SchemaExport(cfg).SetOutputFile(Path.Combine(PathHelper.AppDataPath, "myDDL.sql"));
                    export.Create(true, false);
                });
                factory = config.BuildSessionFactory();
                _cacheSessionFactory[sqlConnectProvider.Name] = factory;
            }

            return(factory);
        }
コード例 #12
0
        public static void Configure(IUnityContainer container)
        {
            var settings      = container.Resolve <Settings>();
            var configuration = new Configuration().DataBaseIntegration(db =>
            {
                db.ConnectionString = settings.ConnectionString;
                db.Dialect <MsSql2008Dialect>();
            });

            configuration.CurrentSessionContext <CurrentSessionContext>();
            var mapper = new ModelMapper();

            Type[] myTypes = Assembly.GetExecutingAssembly().GetExportedTypes();
            mapper.AddMappings(myTypes);
            var mapping = new NHibernateMapper().Map();

            configuration
            .AddMapping(mapping);
            configuration.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new CoordinatesInsertEventListener() };
            configuration.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new CoordinatesUpdateEventListener() };

            var sessionFactory = configuration.BuildSessionFactory();

            container.RegisterInstance(configuration);
            container.RegisterInstance(sessionFactory);

            if (settings.RebuildDatabase)
            {
                var schema = new SchemaExport(configuration);
                schema.Create(false, true);
            }
        }
コード例 #13
0
        // !! MUITO CUIDADO !! - RECRIA BANCO DE DADOS !!
        ////////private static void BuildSchema(FluentConfiguration configuration)
        ////////{
        ////////    var sessionSource = new SessionSource(configuration);
        ////////    var session = sessionSource.CreateSession();
        ////////    sessionSource.BuildSchema(session);
        ////////}

        //////// ESSE BELEZA
        private void BuildSchemaToFile(Configuration cfg, string pathFileName)
        {
            SchemaExport exp = new SchemaExport(cfg);

            exp.SetOutputFile(pathFileName);
            exp.Create(true, false);
        }
コード例 #14
0
        public static IAuthenticationService AuthenticationService()
        {
            if (configured == false)
            {
                string applicationName = "sops";

                IPersistenceConfigurer persistenceConfigurer =
                    MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection"));

                service = new FormsAuthenticationService(applicationName,
                                                         new BCryptStrategy(),
                                                         new ConsoleLogger(),
                                                         persistenceConfigurer,
                                                         configuration =>
                {
                    var se = new SchemaExport(configuration);
                    se.Drop(true, true);
                    se.Execute(true, true, true);

                    var su = new SchemaUpdate(configuration);
                    su.Execute(true, true);
                });
                service.Configure();
                configured = true;
            }

            return(service);
        }
        private void BuildSchema()
        {
            var cfg          = NHConfigurator.Configuration;
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Create(false, true);
        }
コード例 #16
0
        private void ShowCreateDbSql()
        {
            var helper = new NHibernateHelper();
            var export = new SchemaExport(helper.Configuration);

            export.Create(true, false);
        }
コード例 #17
0
        public static void DropCreateSchema(this Configuration configuration)
        {
            var exporter = new SchemaExport(configuration);

            exporter.Drop(false, true);
            exporter.Create(false, true);
        }
コード例 #18
0
        private static void build_schema(Configuration cfg)
        {
            SchemaExport s = new SchemaExport(cfg);

            s.SetOutputFile(Path.Combine(PATH_TO_SCRIPTS, Path.Combine("Up", NAME_OF_SCRIPT)));
            s.Create(true, false);
        }
コード例 #19
0
ファイル: TestDatabaseFactory.cs プロジェクト: AgFlore/vocadb
        private void RecreateSchema(NHibernate.Cfg.Configuration cfg, string connectionStringName)
        {
#if !DEBUG
            return;
#endif

            bool writeOutput = false;

            RunSql(connectionStringName, connection =>
            {
                // NH schema export does not correctly drop all constraints
                // SQL from http://stackoverflow.com/a/26348027
                new SqlCommand(@"
					exec sp_MSforeachtable ""declare @name nvarchar(max); set @name = parsename('?', 1); exec sp_MSdropconstraints @name"";
				"                , connection).ExecuteNonQuery();

                var export = new SchemaExport(cfg);
                if (writeOutput)
                {
                    using (var writer = new StreamWriter(@"C:\Temp\vdb.sql"))
                    {
                        export.Execute(false, true, false, connection, writer);
                    }
                }
                else
                {
                    export.Execute(false, true, false, connection, null);
                }
            });
        }
コード例 #20
0
        public void Test_002_CreateSchema()
        {
            Configuration cfg    = this.TestHelper.GetCfg(AddAssemblies);
            SchemaExport  export = new SchemaExport(cfg);

            export.Create(false, true);
        }
コード例 #21
0
        public void TestCleanup()
        {
            //Reset database data after every run
            SchemaExport exp = new SchemaExport(_cfg);

            exp.Execute(true, true, false);
        }
コード例 #22
0
        public static void Main()
        {
            Configuration cfg = new Configuration();

            cfg.Configure("hibernate.cfg.xml");
            SchemaExport exporter = new SchemaExport(cfg);

            exporter.Create(true, true);

            using (ISessionFactory sf = cfg.BuildSessionFactory())
            {
                using (ISession session = sf.OpenSession())
                {
                    Customer c = new Customer();
                    c.Id        = 1;
                    c.FirstName = "Astor";
                    c.LastName  = "Piazzolla";

                    session.Save(c);
                    session.Flush();
                    session.Evict(c);


                    Customer customer = session.Get <Customer>(1);

                    Debug.Assert(customer.FirstName == "Astor");
                    Debug.Assert(customer.LastName == "PIAZZOLLA");
                }
            }
            Console.WriteLine("Done");
            Console.ReadKey(true);
        }
コード例 #23
0
        public static void Configure(string connectionString, bool dropAndCreateTables = false)
        {
            var cfg = Fluently.Configure()
                      .Database(FluentNHibernate.Cfg.Db.PostgreSQLConfiguration.Standard
                                .ConnectionString(connectionString)
                                .Driver </*NHibernate.Extensions.NpgSql.NpgSqlDriver*/ NpgsqlDriver>()
                                .Dialect <PostGis20Dialect>())
                      .Mappings(x =>
            {
                x.FluentMappings.Add(typeof(GravityVectorMapping <PostGisGeometryType>));
                x.FluentMappings.Add(typeof(NormalRouteMapping <PostGisGeometryType>));
                x.FluentMappings.Add(typeof(DeviationCellMapping <PostGisGeometryType>));
                x.FluentMappings.Add(typeof(NearMissIncidentMapping <PostGisGeometryType>));
            }
                                )
                      .BuildConfiguration()
                      .SetProperty("command_timeout", "-1");

            cfg.AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

            if (dropAndCreateTables)
            {
                var exporter = new SchemaExport(cfg);
                exporter.Drop(false, true);
                exporter.Create(false, true);
            }

            SessionManager.SessionFactory = cfg.BuildSessionFactory();
        }
コード例 #24
0
        protected virtual Configuration FluentlyConfigureSqlite(SqliteDatabase database)
        {
            var filePath = database.FilePath;
            SQLiteConfiguration liteConfiguration =
                SQLiteConfiguration.Standard
                .UsingFile(filePath)
                .ProxyFactoryFactory(typeof(ProxyFactoryFactory));

            var fluentConfig =
                Fluently
                .Configure()
                .Database(liteConfiguration)
                .Mappings(m => m.FluentMappings.AddFromAssembly(GetType().Assembly))
                // Install the database if it doesn't exist
                .ExposeConfiguration(config =>
            {
                if (File.Exists(filePath))
                {
                    return;
                }

                SchemaExport export = new SchemaExport(config);
                export.Drop(false, true);
                export.Create(false, true);
            })
                .BuildConfiguration();

            AddProperties(fluentConfig);

            return(fluentConfig);
        }
コード例 #25
0
        async Task <Configuration> CreateTimeoutManagerObjects()
        {
            var configuration = new Configuration()
                                .DataBaseIntegration(x =>
            {
                x.Dialect <MsSql2012Dialect>();
                x.ConnectionString = Consts.SqlConnectionString;
            });

            if (dbSchemaName != null)
            {
                await CreateDbSchema();

                configuration.SetProperty(Environment.DefaultSchema, dbSchemaNeedsQuoting ? $"[{dbSchemaName}]" : dbSchemaName);
            }

            var mapper = new ModelMapper();

            mapper.AddMapping <TimeoutEntityMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            schemaExport = new SchemaExport(configuration);
            await schemaExport.CreateAsync(false, true);

            return(configuration);
        }
コード例 #26
0
 private void Cleanup()
 {
     Sfi?.Close();
     _sessionFactory = null;
     cfg             = null;
     _schemaExport   = null;
 }
コード例 #27
0
        private static void RecreateDatabase(Configuration configuration)
        {
            SchemaExport export = new SchemaExport(configuration);

            export.Drop(false, true);
            export.Create(false, true);
        }
コード例 #28
0
        private static FluentConfiguration CreateFluentConfiguration()
        {
            return(Fluently.Configure()
                   .Database(MsSqlConfiguration.MsSql2012
                             .ConnectionString(builder => builder.FromConnectionStringWithKey("cnDemo"))
                             )

                   .Mappings(m =>
                             m.AutoMappings.Add(
                                 AutoMap
                                 .AssemblyOf <Product>(new DemoAutomappingConfiguration())
                                 .Conventions.Setup(x =>
            {
                x.Add <PrimaryKeyConvention>();
                x.Add <CustomForeignKeyConvention>();
                x.Add <ColumnNullableConvention>();
            })
                                 .Override <Invoice>(map =>
                                                     map.Map(invoice => invoice.Code).Nullable()
                                                     )
                                 .UseOverridesFromAssemblyOf <Product>()
                                 )
                             )
                   .ExposeConfiguration(cfg =>
            {
                var exporter = new SchemaExport(cfg);
                exporter.Drop(false, true);
                exporter.Create(false, true);
            }));
        }
コード例 #29
0
        public async Task SchemaExport_Export_CreatesExportScriptAsync()
        {
            Configuration configuration = GetConfiguration();
            SchemaExport  export        = new SchemaExport(configuration);
            TextWriter    tw            = new StringWriter();

            await(export.CreateAsync(tw, false));
            string s = tw.ToString();

            var dialect = Dialect.Dialect.GetDialect(configuration.Properties);

            if (dialect.SupportsIfExistsBeforeTableName)
            {
                Assert.IsTrue(s.Contains("drop table if exists Home_Drop"));
                Assert.IsTrue(s.Contains("drop table if exists Home_All"));
            }
            else
            {
                Assert.IsTrue(s.Contains("drop table Home_Drop"));
                Assert.IsTrue(s.Contains("drop table Home_All"));
            }

            Assert.IsTrue(s.Contains("create table Home_All"));
            Assert.IsTrue(s.Contains("create table Home_Export"));
        }
コード例 #30
0
ファイル: DbServer.cs プロジェクト: KreskaDev/DDD
        public string GenerateDatabaseSql(Configuration configuration)
        {
            var sb     = new StringBuilder();
            var export = new SchemaExport(configuration);

            export.Create(s => sb.Append($"{s}\n"), false);
            return(sb.ToString());
        }
コード例 #31
0
ファイル: NHibernateTestFixture.cs プロジェクト: joyoon/mb
 public void SetupTests()
 {
     var se = new SchemaExport(SessionSource.Configuration);
     //se.Drop(false, true);
     //se.Drop(false, true);
     //se.Drop(false, true);
     //se.Create(false, true);
 }
コード例 #32
0
 public void SetUp()
 {
     cfg = new Configuration();
     cfg.Properties["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
     cfg.Properties["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
     cfg.Properties["connection.connection_string"] =
         "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI";
     cfg.Properties["dialect"] = "NHibernate.Dialect.MsSql2000Dialect";
     cfg.Properties["proxyfactory.factory_class"] =
         "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
     cfg.Properties["show_sql"] = "true";
     cfg.AddAssembly("BlogSharp.NHibernate");
     factory = cfg.BuildSessionFactory();
     var export = new SchemaExport(cfg);
     export.Execute( true, false, true);
 }
コード例 #33
0
        public void SetUp()
        {
            cfg=Fluently.Configure()
                .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<UserMap>())
                .Database(MsSqlConfiguration.MsSql2008
                            .AdoNetBatchSize(20)
                            .ConnectionString(stringBuilder=>
                                              		stringBuilder.Database("test")
                                              			.TrustedConnection()
                                              			.Server("."))
                            .ShowSql()
                            .Raw("hbm2ddl.keywords", "auto-quote")
                ).BuildConfiguration();

            factory = cfg.BuildSessionFactory();
            var export = new SchemaExport(cfg);
            export.Execute(true, true, false);
        }
        /// <summary>
        /// Gets an NHibernate session for an in-memory database.
        /// </summary>
        /// <returns>
        /// A session for an in-memory database.
        /// </returns>
        private static ISession GetInMemoryDatabaseSession()
        {
            Configuration configuration = null;
            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard
                        .InMemory()
                        .ShowSql())
                .Mappings(
                    m => m.FluentMappings.AddFromAssemblyOf<HistoricPriceMap>())
                .ExposeConfiguration(
                    cfg => configuration = cfg)
                .BuildSessionFactory();
            var session = sessionFactory.OpenSession();

            var schemaExport = new SchemaExport(configuration);
            schemaExport.Execute(true, true, false, session.Connection, null);

            return session;
        }
コード例 #35
0
 public void TearDown()
 {
     factory = cfg.BuildSessionFactory();
     var export = new SchemaExport(cfg);
     export.Execute(true, false, true);
 }