Example #1
0
 static void Main(string[] args)
 {
     NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
     cfg.Configure();
     NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
     schema.Create(false, true);
 }
Example #2
0
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
              kernel.Bind<IContextDataProvider>()
            .To<UsernameContextDataProvider>();
              var sl = new NinjectServiceLocator(kernel);
              ServiceLocator.SetLocatorProvider(() => sl);

              var namingStrategy = new NamingStrategy();
              var auditColumnSource = new CtxAuditColumnSource();
              var cfg = new Configuration().Configure();
              new TriggerAuditing(cfg, namingStrategy,
            auditColumnSource).Configure();

              var sessionFaculty = cfg.BuildSessionFactory();

              var se = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
              se.Execute(true, true, false);

              var padlock = new Product()
              {
            Name = "Padlock",
            Description = "Secure, weather resistant",
            UnitPrice = 8.36M
              };
              Guid padlockId;

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlockId = (Guid)session.Save(padlock);
              tx.Commit();
            }
              }

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlock = session.Get<Product>(padlockId);
              padlock.UnitPrice = 0.10M;
              padlock.Description = "Not so secure, actually.";
              session.SaveOrUpdate(padlock);
              tx.Commit();
            }
              }

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlock = session.Load<Product>(padlockId);
              session.Delete(padlock);
              tx.Commit();
            }
              }
        }
Example #3
0
        public void DropDatabase()
        {
            //closing the session makes sure it's not using the database
            //thus allowing the drop statements to run quickly
            NHibernateHelper.CloseSession();

            SchemaExport ddlExport = new SchemaExport(NHibernateHelper.Configuration);
            ddlExport.Drop(false, true);
        }
 public void UpdateDatabase(bool update)
 {
     using (var s = OpenStatelessSession())
     {
         var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(_config);
         
         schemaExport.Execute(false, update, false, s.Connection, Console.Out);
     }
 }
Example #5
0
        public void CreateDatabase()
        {
            SchemaExport ddlExport = new SchemaExport(NHibernateHelper.Configuration);

            //if we want to actually look at the DDL generated, we can do this
            ddlExport.SetOutputFile("c:\\NHiA.sql");

            ddlExport.Create(true, true);
        }
Example #6
0
        public void CreateDatabase()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();

            var schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            schema.Execute(true, false, false);
        }
        public void _TestTestFixtureSetUp()
        {

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();

            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);

            _sessionManager = new DataAccessLayer.NHibernateSessionManager();

            ISessionFactory sessionFactory = _sessionManager.GetSession().SessionFactory;

            base.DatabaseTestFixtureSetUp();
        }
Example #8
0
        static void Main(string[] args)
        {
            var cfg = new Configuration().Configure();
              var sessionFaculty = cfg.BuildSessionFactory();

              var se = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
              se.Execute(true, true, false);

              var padlock = new Product()
              {
            Name = "Padlock",
            Description = "Secure, weather resistant",
            UnitPrice = 8.36M
              };
              Guid padlockId;

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlockId = (Guid)session.Save(padlock);
              tx.Commit();
            }
              }

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlock = session.Get<Product>(padlockId);
              padlock.UnitPrice = 0.10M;
              padlock.Description = "Not so secure, actually.";
              session.SaveOrUpdate(padlock);
              tx.Commit();
            }
              }

              using (var session = sessionFaculty.OpenSession())
              {
            using (var tx = session.BeginTransaction())
            {
              padlock = session.Load<Product>(padlockId);
              session.Delete(padlock);
              tx.Commit();
            }
              }
        }
Example #9
0
        public static void CreateSchema(bool executeOnDatabase)
        {
            var configuration = GetConfiguration();
            var schemaExport  = new NHibernate.Tool.hbm2ddl.SchemaExport(configuration);

            using (TextWriter writer = File.CreateText("BiebDatabase.sql"))
            {
                if (executeOnDatabase)
                {
                    using (var schemaCreationSession = configuration.BuildSessionFactory().OpenSession())
                    {
                        schemaExport.Execute(true, true, false, schemaCreationSession.Connection, writer);
                    }
                }
                else
                {
                    schemaExport.Execute(true, false, false, null, writer);
                }
            }
        }
Example #10
0
        public static void CreateSchemaFromEntitiesAssembly(string connectionName, string fileNameToExportSql, bool executeSql)
        {
            var cnp =
                NHibernateConfigurationManager.ConfigurationHelper.Create(connectionName);

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

            var ddlExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            var exportFile = !string.IsNullOrEmpty(fileNameToExportSql);

            if (exportFile)
            {
                ddlExport.SetOutputFile(fileNameToExportSql);
            }
            ddlExport.Create(exportFile, executeSql);
            /*
            var ddlupadte = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);

            ddlupadte.Execute(true, true);*/
        }
Example #11
0
        public void Hbm2DdlOutput()
        {
            ContextualKeyRoutingConnectionProvider.CurrentRoutingKey = AnyConnectionRoutingKey;

            var connString = GetCurrentConnectionString();
            var cfg        = GetNHibernateConfiguration(connString);

            var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            schemaExport.SetOutputFile(@"..\..\sql\hbm2ddl_drop.sql").SetDelimiter(SqlDelimiter).Drop(true, false);
            schemaExport.SetOutputFile(@"..\..\sql\hbm2ddl_create.sql").SetDelimiter(SqlDelimiter).Create(true, false);

            var sb           = new StringBuilder();
            var schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);

            schemaUpdate.Execute(s => sb.Append(s).Append(SqlDelimiter), false);

            using (var writer = new StreamWriter(@"..\..\sql\hbm2ddl_update.sql"))
            {
                writer.Write(sb.ToString());
            }
        }
Example #12
0
        public void MyTestInitialize()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.Properties["connection.driver_class"]      = "NHibernate.Driver.SqlClientDriver";
            config.Properties["connection.provider"]          = "NHibernate.Connection.DriverConnectionProvider";
            config.Properties["connection.connection_string"] = Helper.ClassicTestDB_SQLExpress_ConnectionString;
            config.Properties["dialect"] = "NHibernate.Dialect.MsSql2008Dialect";
            config.Properties["proxyfactory.factory_class"] = "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu";
            config.AddAssembly(typeof(Customer).Assembly);
            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(config);
            schemaExport.Execute(false, true, false);

            customer = new Customer
            {
                //Id = Guid.NewGuid(),
                Birth     = DateTime.Now,
                Email     = "*****@*****.**",
                FirstName = "dax",
                LastName  = "net",
                Password  = "******",
                Username  = "******"
            };
        }
        public void MyTestInitialize()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.Properties["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
            config.Properties["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
            config.Properties["connection.connection_string"] = Helper.ClassicTestDB_SQLExpress_ConnectionString;
            config.Properties["dialect"] = "NHibernate.Dialect.MsSql2008Dialect";
            config.Properties["proxyfactory.factory_class"] = "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu";
            config.AddAssembly(typeof(Customer).Assembly);
            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(config);
            schemaExport.Execute(false, true, false);

            customer = new Customer
            {
                //Id = Guid.NewGuid(),
                Birth = DateTime.Now,
                Email = "*****@*****.**",
                FirstName = "dax",
                LastName = "net",
                Password = "******",
                Username = "******"
            };
        }
Example #14
0
        //
        // GET: /Install/
        public ActionResult Step1()
        {
            var SchemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(RegisterNHibernate.Configure());
            SchemaExport.Drop(false, true);
            SchemaExport.Create(false, true);

            var site = new Site { Name = "vbgCMS" };
            var session = ServiceLocator.Current.GetInstance<ISession>();

            using (var transaction = session.BeginTransaction())
            {
                try
                {
                    session.Save(site);
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }

            return RedirectToAction("Completed");
        }
Example #15
0
 /// <summary>
 /// Creates ddl and/or runs it against the database.
 /// </summary>
 /// <param name="script">true if the ddl should be outputted in the Console.</param>
 /// <param name="export">true if the ddl should be executed against the Database.</param>
 public static void CreateDatabase(bool script, bool export)
 {
     NHibernate.Tool.hbm2ddl.SchemaExport schemaExport =
         new NHibernate.Tool.hbm2ddl.SchemaExport(SessionManagerFactory.SessionManager.Config);
     schemaExport.Create(script, export);
 }
Example #16
0
        /// <summary>
        /// Create the specified database schema category.
        /// Remember that these methods delete any existing data on the database and recreate the database structure.
        /// </summary>
        /// <param name="schemaCategory"></param>
        public void CreateSchemaTable(string schemaCategory)
        {
            NHibernate.Cfg.Configuration hibConfig = _Configuration.CreateNHibernateConfiguration(ConfigurationFlags.Settings);

            Type[] entities = GetEntities(schemaCategory);

            foreach (Type ent in entities)
                hibConfig.AddClass(ent);

            var ddlExport = new NHibernate.Tool.hbm2ddl.SchemaExport(hibConfig);
            ddlExport.Create(false, true);
        }
Example #17
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 #18
0
 /// <summary>
 /// Creates ddl and/or runs it against the database.
 /// </summary>
 /// <param name="script">true if the ddl should be outputted in the Console.</param>
 /// <param name="export">true if the ddl should be executed against the Database.</param>
 public static void CreateDatabase(bool script, bool export)
 {
     NHibernate.Tool.hbm2ddl.SchemaExport schemaExport =
         new NHibernate.Tool.hbm2ddl.SchemaExport(SessionManagerFactory.SessionManager.Config);
     schemaExport.Create(script, export);
 }
		public static void CreateDatabase(NHibernate.Cfg.Configuration configuration)
		{
			NHibernate.Tool.hbm2ddl.SchemaExport se =
				new NHibernate.Tool.hbm2ddl.SchemaExport(configuration);
			se.Create(true, true);
		}