Example #1
0
        public static ISessionFactory CreateSessionFactory(string filePath, bool mainSession)
        {
            Configuration configuration = new Configuration()
                                          .SetProperty("dialect", typeof(CustomSQLiteDialect).AssemblyQualifiedName)
                                          .SetProperty("hibernate.cache.use_query_cache", "true")
                                          .SetProperty("proxyfactory.factory_class", typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName)
                                          //.SetProperty("adonet.batch_size", batchSize.ToString())
                                          .SetProperty("connection.connection_string", "Data Source=" + filePath + ";Version=3;")
                                          .SetProperty("connection.driver_class", typeof(NHibernate.Driver.SQLite20Driver).AssemblyQualifiedName)
                                          .SetProperty("connection.provider", typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName)
                                          .SetProperty("connection.release_mode", "on_close")
            ;

            ConfigureMappings(configuration);

            ISessionFactory sessionFactory = null;

            lock (mutex)
                sessionFactory = configuration.BuildSessionFactory();

            if (mainSession)
            {
                sessionFactory.OpenStatelessSession().CreateSQLQuery(@"PRAGMA default_cache_size=500000;
                                                                   PRAGMA temp_store=MEMORY").ExecuteUpdate();

                var schema = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
                schema.Execute(false, true);
            }

            return(sessionFactory);
        }
Example #2
0
 public void Execute()
 {
     NH.Cfg.Configuration _configuration = SessionFactory.GetConfiguration();
     //NH.Tool.hbm2ddl.SchemaExport se = new NH.Tool.hbm2ddl.SchemaExport(_configuration);
     //se.Execute(false, false, true);
     NH.Tool.hbm2ddl.SchemaUpdate su = new NH.Tool.hbm2ddl.SchemaUpdate(_configuration);
     su.Execute(false, true);
 }
Example #3
0
        private void BuildSchema()
        {
            //NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(Cfg);
            //schemaExport.Execute(false, true, false, Connection, null);

            NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(this.Cfg);
            schemaUpdate.Execute(false, true);
        }
        public static void UpdateSchema()
        {
            var configuration = new Configuration();

            configuration.Configure();
            //   configuration.AddAssembly(typeof(HydroDataCenter.Models.Station).Assembly);
            configuration.AddAssembly(typeof(HydroDataCenterEntity.Models.Site).Assembly);

            NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate
                = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
            schemaUpdate.Execute(true, true);
        }
Example #5
0
        public static void Init()
        {
            Configuration cfg = new Configuration();
            cfg.Configure("hibernate.cfg.xml");

//            cfg.AddAssembly(typeof(Codes.Meteocode).Assembly);

            NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate
                = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
            schemaUpdate.Execute(true, true);

            sessionFactory = cfg.BuildSessionFactory();
        }
Example #6
0
        public static void UpdateSchema()
        {
            var configuration = new Configuration();

            configuration.Configure();
            configuration.AddAssembly("IndexMobileEntity");

            NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate
                = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
            schemaUpdate.Execute(true, true);

            foreach (var item in schemaUpdate.Exceptions)
            {
                Console.WriteLine(item.Message + "\n\n" + item.Source + "\n\n" + item.StackTrace + "\n\n");
                if (item.InnerException != null)
                {
                    Console.WriteLine(item.InnerException.Message);
                }
            }
        }
Example #7
0
        public static ISessionFactory CreateSessionFactory(string filePath, bool mainSession)
        {
            Configuration configuration = new Configuration()
                .SetProperty("dialect", typeof(CustomSQLiteDialect).AssemblyQualifiedName)
                .SetProperty("hibernate.cache.use_query_cache", "true")
                .SetProperty("proxyfactory.factory_class", typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName)
                //.SetProperty("adonet.batch_size", batchSize.ToString())
                .SetProperty("connection.connection_string", "Data Source=" + filePath + ";Version=3;")
                .SetProperty("connection.driver_class", typeof(NHibernate.Driver.SQLite20Driver).AssemblyQualifiedName)
                .SetProperty("connection.provider", typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName)
                .SetProperty("connection.release_mode", "on_close")
                ;

            ConfigureMappings(configuration);

            ISessionFactory sessionFactory = null;
            lock (mutex)
                sessionFactory = configuration.BuildSessionFactory();

            if (mainSession)
            {
                sessionFactory.OpenStatelessSession().CreateSQLQuery(@"PRAGMA default_cache_size=500000;
                                                                   PRAGMA temp_store=MEMORY").ExecuteUpdate();

                var schema = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
                schema.Execute(false, true);
            }

            return sessionFactory;
        }
Example #8
0
        public static void UpdateSchemaFromEntitiesAssembly(string connectionName, string fileNameToExportSql, bool executeSql)
        {
            var cnp =
                NHibernateConfigurationManager.ConfigurationHelper.Create(connectionName);

            var cfg = cnp.CreateNHibernateConfiguration(ConfigurationFlags.Settings | ConfigurationFlags.MappingsToExport);

            var ddlUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);

            var exportFile = !string.IsNullOrEmpty(fileNameToExportSql);

            if (exportFile)
            {
                var queries = string.Empty;

                ddlUpdate.Execute(delegate(string s) { queries = string.Format("{0};{1}", s, Environment.NewLine); }, executeSql);

                if (!String.IsNullOrEmpty(queries))
                    File.WriteAllText(fileNameToExportSql, queries);
            }

            else
            {
                ddlUpdate.Execute(false, true);
            }

            if (ddlUpdate.Exceptions.Count > 0)
            {
                throw ddlUpdate.Exceptions[0];
            }
        }
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            // TODO: It should be possible to define this config in some XML file as well
            // Google to find out how

            var cfg = new NHibernate.Cfg.Configuration();
            {
                // This way of configuring works, but I want to try out the xml config file
                //cfg.DataBaseIntegration(x =>
                //{
                //    x.ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=NHibernate01;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                //    x.Driver<SqlClientDriver>();
                //    x.Dialect<MsSqlCeDialect>();
                //});

                //cfg.AddAssembly(Assembly.GetExecutingAssembly());
            }
            {
                // Use xml for configuration
                // Add hibernate.cfg.xml as Embedded Resource in a folder named Configuration
                // use cfg.Configure(assembly, resourceName) version
                // The other version cfg.Configure(resourceName) always searches for the file in startup project

                var assembly = Assembly.GetExecutingAssembly();
                var assemblyName = assembly.GetName().Name;
                var manifestResourceName = "Configuration.hibernate.cfg.xml";

                cfg.Configure(assembly, $"{assemblyName}.{manifestResourceName}"); // ORM_NHibernate.Configuration.hibernate.cfg.xml


                //// You can also add Mappings by Code .. Note here that we have not defined any HBM for Teacher class
                //// Also not that we've updated the Student HBM file to set VARCHAR(1000) instead of the default 255
                //var mapper = new NHibernate.Mapping.ByCode.ConventionModelMapper();
                //cfg.AddMapping(mapper.CompileMappingFor(new[] { typeof(BusinessObjects.Teacher) }));

                foreach (var mapping in cfg.ClassMappings)
                {
                    string x = $"(1) {mapping.ClassName}, (2) {mapping.Discriminator}, (3) {mapping.DiscriminatorValue}, (4) {mapping.IsDiscriminatorValueNotNull}";
                    System.Diagnostics.Debug.WriteLine(x);
                }



                var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
                schemaExport.SetOutputFile(@"db.Postgre.sql").Execute(useStdOut: true, execute: true, justDrop: false);

                //// Example Schema Export
                ///
                /*
                 * 
                    create table ActorRole (
                        id INTEGER not null,
                       Actor VARCHAR(255) not null,
                       Role VARCHAR(255) not null,
                       MovieId INTEGER,
                       ActorIndex INTEGER,
                       primary key (id)
                    )

                    create table product (
                        id INTEGER not null,
                       Name VARCHAR(255) not null,
                       description VARCHAR(100),
                       UnitPrice NUMERIC(18,4) not null,
                       primary key (id)
                    )

                    create table Book (
                        Id INTEGER not null,
                       ISBN VARCHAR(255),
                       Author VARCHAR(255),
                       primary key (Id)
                    )

                    create table Movie (
                        Id INTEGER not null,
                       Director VARCHAR(255),
                       primary key (Id)
                    )

                    alter table ActorRole
                        add index (MovieId),
                        add constraint FK_B3337C3E
                        foreign key (MovieId)
                        references Movie (Id)

                    alter table Book
                        add index (Id),
                        add constraint FK_2E5EFA32
                        foreign key (Id)
                        references product (id)

                    alter table Movie
                        add index (Id),
                        add constraint FK_13C98C6D
                        foreign key (Id)
                        references product (id)

                    create table hibernate_unique_key (
                         next_hi INTEGER
                    )

                    insert into hibernate_unique_key values ( 1 )
                 * 
                 * */


                // Alternately, we can use SchemaUpdate.Execute, as in done in 1P
                NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
                schemaUpdate.Execute(useStdOut: true, doUpdate: true);

                // Note
                // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute
                // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement 
                // to tell the diff in schema, and only this got executed:
                /*
                    alter table Movie
                        add column NewProp VARCHAR(255)
                 * 
                 * */
                //
                // However, it does not work as expected all the times, for eg, 
                // if I rename a column in HBM, it just adds a new column with new name
                // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged
                // So we will need manual scripts for migration
                //

                cfg.SetInterceptor(new AuditInterceptor());
            }

            return cfg;
        }
Example #10
0
 /// <summary>
 /// 更新数据库结构
 /// </summary>
 public static void UpdateSchema()
 {
     NH.Tool.hbm2ddl.SchemaUpdate su = new NH.Tool.hbm2ddl.SchemaUpdate(configuration);
     su.Execute(true, true);
 }