static SessionFactory() { NHConfiguration = new NHibernate.Cfg.Configuration(); NHConfiguration.AddAssembly(Assembly.GetExecutingAssembly().FullName); SchemaMetadataUpdater.QuoteTableAndColumns(NHConfiguration); NHSessionFactory = NHConfiguration.BuildSessionFactory(); }
private static void BuildSchema(Configuration config) { // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it SchemaMetadataUpdater.QuoteTableAndColumns(config); new SchemaUpdate(config).Execute(false, true); }
protected override void BuildMappings(Configuration conf) { HbmMapping mapping = GetMappings(); conf.AddDeserializedMapping(mapping, "NHSchemaTest"); SchemaMetadataUpdater.QuoteTableAndColumns(conf); }
private static void Init() { Configuration config = new Configuration(); config.SessionFactoryName("BuiltIt"); config.DataBaseIntegration(db => { db.Dialect <MsSql2008DialectBugFix>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = System.Configuration .ConfigurationManager .ConnectionStrings["SamanCnn"].ToString(); db.Timeout = 30; db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); HbmMapping mapping = GetMappings(); config.AddDeserializedMapping(mapping, "Saman"); SchemaMetadataUpdater.QuoteTableAndColumns(config); _sessionFactory = config.BuildSessionFactory(); }
/// <summary> /// Configure NHibernate /// </summary> private static Configuration ConfigureNHibernate() { Configuration configure = new Configuration(); configure.SessionFactoryName("SessionFactory"); configure.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = RegtestingServerConfiguration.DefaultConnectionString; //db.Timeout = 10; //For testing //db.LogFormattedSql = true; //db.LogSqlInConsole = true; //db.AutoCommentSql = true; }); HbmMapping hbmMapping = GetMappings(); configure.AddDeserializedMapping(hbmMapping, "NHMapping"); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure); }
public async Task UpdateReservedWordsInDialectAsync() { var reservedDb = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var configuration = TestConfigurationHelper.GetDefaultConfiguration(); var dialect = Dialect.Dialect.GetDialect(configuration.Properties); var connectionHelper = new ManagedProviderConnectionHelper(configuration.Properties); await(connectionHelper.PrepareAsync(CancellationToken.None)); try { var metaData = dialect.GetDataBaseSchema(connectionHelper.Connection); foreach (var rw in metaData.GetReservedWords()) { reservedDb.Add(rw.ToLowerInvariant()); } } finally { connectionHelper.Release(); } var sf = (ISessionFactoryImplementor)configuration.BuildSessionFactory(); await(SchemaMetadataUpdater.UpdateAsync(sf, CancellationToken.None)); var match = reservedDb.Intersect(sf.Dialect.Keywords, StringComparer.OrdinalIgnoreCase); // tests that nothing in the first metaData.GetReservedWords() is left out of the second metaData.GetReservedWords() call. // i.e. always passes. Assert.That(match, Is.EquivalentTo(reservedDb)); }
/// <summary> /// Scripts the database objects creation for storing IdentityServer data. /// </summary> /// <param name="scriptFileName">Output file name</param> /// <param name="configuration">NHibernate Configuration object that represents the database configuration to script.</param> /// <param name="configurationStoreOptions">Options for configuration store.</param> /// <param name="operationalStoreOptions">Options for operational store.</param> /// <remarks> /// Configuration store options and operational store options are needed to detect the schema for each database object. /// </remarks> public static void CreateSchemaScriptForDatabase( string scriptFileName, Configuration configuration, ConfigurationStoreOptions configurationStoreOptions, OperationalStoreOptions operationalStoreOptions) { if (configurationStoreOptions == null) { throw new ArgumentNullException(nameof(configurationStoreOptions)); } if (operationalStoreOptions == null) { throw new ArgumentNullException(nameof(operationalStoreOptions)); } configuration.AddConfigurationStoreMappings(configurationStoreOptions); configuration.AddOperationalStoreMappings(operationalStoreOptions); var dialect = Dialect.GetDialect(configuration.Properties); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, dialect); new SchemaExport(configuration) .SetOutputFile(scriptFileName) .SetDelimiter(";") .Execute(true, false, false); }
private static Configuration ConfigureNHibernate() { var configure = new Configuration(); configure.SessionFactoryName("BuildIt"); configure.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.Driver <Sql2008ClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = "TestDB"; db.Timeout = 10; // enabled for testing db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); var mapping = GetMappings(); configure.AddDeserializedMapping(mapping, "NHSchemaTest"); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure); }
private static void BuildSessionFactory(string userName, string connectionString) { var currentAssembly = typeof(NHibernateSessionFactory).Assembly; var manifestName = currentAssembly.ManifestModule.Name.Replace(".dll", string.Empty); var configuration = new Configuration(); configuration.SetProperty(Environment.ConnectionString, connectionString); configuration.Configure(currentAssembly, $"{manifestName}.NHibernate.hibernate.cfg.xml"); configuration.AddAssembly(currentAssembly); configuration.SetProperty(Environment.UseSqlComments, "false"); var mappings = GetMappings(); configuration.AddDeserializedMapping(mappings, manifestName); SchemaMetadataUpdater.QuoteTableAndColumns(configuration); configuration.DataBaseIntegration(db => { db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); SessionFactoryCache.Add(userName, configuration.BuildSessionFactory()); }
private static ISessionFactory createSessionFactory() { var configure = new Configuration(); configure.SessionFactoryName(sessionName); configure.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = sessionName; db.Timeout = 10; }); // mapping by code var mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetExecutingAssembly() .GetExportedTypes()); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); // mapping by xml configure.AddAssembly("MITD.PMS.Persistence.NH"); //Other setting configure.AddDeserializedMapping(mapping, sessionName); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure.BuildSessionFactory()); }
public void UpdateReservedWordsInDialect() { var reservedDb = new HashedSet <string>(); var configuration = TestConfigurationHelper.GetDefaultConfiguration(); var dialect = Dialect.Dialect.GetDialect(configuration.Properties); var connectionHelper = new ManagedProviderConnectionHelper(configuration.Properties); connectionHelper.Prepare(); try { var metaData = dialect.GetDataBaseSchema(connectionHelper.Connection); foreach (var rw in metaData.GetReservedWords()) { reservedDb.Add(rw.ToLowerInvariant()); } } finally { connectionHelper.Release(); } var sf = (ISessionFactoryImplementor)configuration.BuildSessionFactory(); SchemaMetadataUpdater.Update(sf); var match = reservedDb.Intersect(sf.Dialect.Keywords); Assert.That(match, Is.EquivalentTo(reservedDb)); }
public void WhenConfiguredOnlyExplicitAutoQuote() { var configuration = TestConfigurationHelper.GetDefaultConfiguration(); var configuredDialect = Dialect.Dialect.GetDialect(); if (!configuredDialect.DefaultProperties.ContainsKey(Environment.ConnectionDriver)) { Assert.Ignore(GetType() + " does not apply to " + configuredDialect); } configuration.Properties.Remove(Environment.ConnectionDriver); configuration.AddResource("NHibernate.Test.Tools.hbm2ddl.SchemaMetadataUpdaterTest.HeavyEntity.hbm.xml", GetType().Assembly); SchemaMetadataUpdater.QuoteTableAndColumns(configuration); var cm = configuration.GetClassMapping(typeof(Order)); Assert.That(cm.Table.IsQuoted); var culs = new List <Column>(cm.Table.ColumnIterator); Assert.That(GetColumnByName(culs, "From").IsQuoted); Assert.That(GetColumnByName(culs, "And").IsQuoted); Assert.That(GetColumnByName(culs, "Select").IsQuoted); Assert.That(!GetColumnByName(culs, "Name").IsQuoted); }
public InMemoryNHibernateSessionSource(IEnumerable <Assembly> mappingAssemblies) { var configuration = new Configuration(); configuration.DataBaseIntegration(cfg => { cfg.ConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared"; cfg.Driver <SQLite20Driver>(); cfg.Dialect <SQLiteDialect>(); cfg.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; cfg.SchemaAction = SchemaAutoAction.Update; }); configuration.AddCodeMappingsFromAssemblies(mappingAssemblies); SchemaMetadataUpdater.QuoteTableAndColumns(configuration); _factory = configuration.BuildSessionFactory(); _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd = _factory.OpenSession(); _connection = _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd.Connection; new SchemaExport(configuration).Execute( script: false, export: true, justDrop: false, connection: _connection, exportOutput: null); }
public static Configuration ConfigureNHibernate() { var cfg = new Configuration(); cfg.DataBaseIntegration(db => { db.Dialect <MsSql2012Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString; db.Timeout = 10; db.LogFormattedSql = true; db.LogSqlInConsole = true; //db.AutoCommentSql = true; }); var mapping = GetAllMappingsFromAssembly(); cfg.AddDeserializedMapping(mapping, null); SchemaMetadataUpdater.QuoteTableAndColumns(cfg); return(cfg); }
public ISessionFactory Build() { var configuration = new Configuration(); configuration.SessionFactoryName(_sessionFactoryName); configuration.DataBaseIntegration(db => { db.Dialect <MsSql2012Dialect>(); db.Driver <YekeSqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = ConnectionString; db.Timeout = 30; }); configuration.AddAssembly(_mappingAssembly); var modelMapper = new ModelMapper(); modelMapper.BeforeMapClass += (mi, t, map) => map.DynamicUpdate(true); modelMapper.AddMappings(_mappingAssembly.GetExportedTypes()); AddDomainEventListener(configuration); var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(mappingDocument, _sessionFactoryName); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, new MsSql2012Dialect()); return(configuration.BuildSessionFactory()); }
public static ISessionFactory Build() { var configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.Dialect <PostgreSQLDialect>(); db.Driver <NpgsqlDriver>(); db.ConnectionProvider <DriverConnectionProvider>(); db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = "database"; db.Timeout = 10; // enabled for testing db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); var mapper = new ModelMapper(); mapper.AddMappings(typeof(ArticleMap).Assembly.ExportedTypes); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mapping); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, new PostgreSQLDialect()); return(configuration.BuildSessionFactory()); }
/// <summary> /// Adds NHibernate core components to the DI system. /// </summary> /// <param name="builder">The builder.</param> /// <param name="databaseConfiguration">NHibernate database configuration.</param> /// <param name="configurationStoreOptions">Configuration store options (needed to configure NHibernate mappings).</param> /// <param name="operationalStoreOptions">Operational store options (needed to configure NHibernate mappings).</param> private static IIdentityServerBuilder AddNHibernatePersistenceSupport( this IIdentityServerBuilder builder, NHibernate.Cfg.Configuration databaseConfiguration, ConfigurationStoreOptions configurationStoreOptions, OperationalStoreOptions operationalStoreOptions) { // Adds NHibernate mappings databaseConfiguration.AddConfigurationStoreMappings(configurationStoreOptions); databaseConfiguration.AddOperationalStoreMappings(operationalStoreOptions); //We need this to quote fields named with reserved keyword SchemaMetadataUpdater.QuoteTableAndColumns(databaseConfiguration, Dialect.GetDialect(databaseConfiguration.Properties)); // Registers NHibernate components builder.Services.AddSingleton(databaseConfiguration.BuildSessionFactory()); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenSession()); }); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenStatelessSession()); }); return(builder); }
public async Task ExplicitAutoQuoteAsync() { var configuration = TestConfigurationHelper.GetDefaultConfiguration(); configuration.AddResource("NHibernate.Test.Tools.hbm2ddl.SchemaMetadataUpdaterTest.HeavyEntity.hbm.xml", GetType().Assembly); var dialect = Dialect.Dialect.GetDialect(configuration.GetDerivedProperties()); dialect.Keywords.Add("Abracadabra"); await(SchemaMetadataUpdater.UpdateAsync(configuration, dialect, CancellationToken.None)); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, dialect); var cm = configuration.GetClassMapping(typeof(Order)); Assert.That(cm.Table.IsQuoted); var culs = new List <Column>(cm.Table.ColumnIterator); Assert.That(GetColumnByName(culs, "From").IsQuoted); Assert.That(GetColumnByName(culs, "And").IsQuoted); Assert.That(GetColumnByName(culs, "Select").IsQuoted); Assert.That(GetColumnByName(culs, "Abracadabra").IsQuoted); Assert.That(!GetColumnByName(culs, "Name").IsQuoted); }
public ISessionFactory GetSessionFactory() { NHibernateProfiler.Initialize(); var config = Fluently.Configure() .Database(_databaseConfig) .Mappings(m => m.AutoMappings .Add(AutoMap.AssemblyOf <NHibernateConfiguration <SqlClientDriver> >() .Where(type => type.Namespace != null && type.Namespace.EndsWith("Entities")) .UseOverridesFromAssemblyOf <NHibernateConfiguration <SqlClientDriver> >() ) ) // Ensure batching is used .ExposeConfiguration(c => c.SetProperty(Environment.BatchSize, "10")) // Turn off cache to make sure all calls actually go to the database .ExposeConfiguration(c => c.SetProperty(Environment.UseQueryCache, "false")) .ExposeConfiguration(c => c.SetProperty(Environment.UseSecondLevelCache, "false")); if (typeof(LocalTestingReliableSql2008ClientDriver).IsAssignableFrom(typeof(T))) { config.ExposeConfiguration(c => c.SetProperty(Environment.TransactionStrategy, typeof(ReliableAdoNetWithDistributedTransactionFactory).AssemblyQualifiedName)); } var nhConfig = config.BuildConfiguration(); SchemaMetadataUpdater.QuoteTableAndColumns(nhConfig); var validator = new SchemaValidator(nhConfig); validator.Validate(); return(config.BuildSessionFactory()); }
private void BuildSchema(Configuration config, IInterceptor interceptor, DbConnectionString.DataBaseIntegration needValidate) { SchemaMetadataUpdater.QuoteTableAndColumns(config, new SbDialect()); #if DEBUG if (interceptor != null) { config.SetInterceptor(interceptor); } #endif // var eventPublisherListener = new PublishEventsListener(_publisher); config.SetListener(ListenerType.PostCommitDelete, _publisher); config.SetListener(ListenerType.Delete, new SoftDeleteEventListener()); config.SetListener(ListenerType.PostCommitInsert, _publisher); config.SetListener(ListenerType.PostCommitUpdate, _publisher); config.SetListener(ListenerType.PostCollectionUpdate, _publisher); foreach (var t in Assembly .GetExecutingAssembly() .GetTypes() .Where(t => typeof(AbstractAuxiliaryDatabaseObject).IsAssignableFrom(t))) { config.AddAuxiliaryDatabaseObject(Activator.CreateInstance(t) as IAuxiliaryDatabaseObject); } //var enversConf = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration(); //enversConf.Audit<Document>() // .Exclude(x => x.Transactions) // .ExcludeRelationData(x => x.University) // .Exclude(x => x.Votes) // .Exclude(x => x.Course) // .Exclude(x => x.User) // .Exclude(x => x.Status.FlaggedUser) // .ExcludeRelationData(x => x.Tags); //config.IntegrateWithEnvers(enversConf); config.LinqToHqlGeneratorsRegistry <MyLinqToHqlGeneratorsRegistry>(); //config.SessionFactory().Caching.WithDefaultExpiration(TimeConst.Day); //config.Properties.Add("cache.default_expiration",$"{TimeConst.Day}"); //config.Properties.Add("cache.use_sliding_expiration",bool.TrueString.ToLowerInvariant()); switch (needValidate) { case DbConnectionString.DataBaseIntegration.None: break; case DbConnectionString.DataBaseIntegration.Validate: config.DataBaseIntegration(dbi => dbi.SchemaAction = SchemaAutoAction.Validate); break; case DbConnectionString.DataBaseIntegration.Update: config.DataBaseIntegration(dbi => dbi.SchemaAction = SchemaAutoAction.Update); break; } }
public void SchemaExport() { Configuration conf = ConfigureNHibernate(); conf.AddDeserializedMapping(GetMapping(), "Animals_Domain"); SchemaMetadataUpdater.QuoteTableAndColumns(conf); ActionAssert.NotThrow(() => new SchemaExport(conf).Create(false, true)); new SchemaExport(conf).Drop(false, true); }
public static void Setup() { NHConfiguration = configureNHibernate(); HbmMapping mapping = getMappings(); NHConfiguration.AddDeserializedMapping(mapping, "NHibernate32Test"); SchemaMetadataUpdater.QuoteTableAndColumns(NHConfiguration); SessionFactory = NHConfiguration.BuildSessionFactory(); }
public static void ApplySchemaChanges() { Configuration cfg = GetConfiguration(); SchemaMetadataUpdater.QuoteTableAndColumns(cfg); var update = new SchemaUpdate(cfg); update.Execute(true, true); }
static void Main(string[] args) { const string ticker = "test2"; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; var testQuote1 = new StockQuote { Ticker = ticker, Date = 20180101, Open = 11, High = 12, Low = 10, Close = 11.2, Volume = 100 }; var testQuote2 = new StockQuote { Ticker = ticker, Date = 20180102, Open = 11, High = 12, Low = 10, Close = 11.2, Volume = 100 }; var stock = new Company { Ticker = ticker, Quotes = new Collection <StockQuote> { testQuote2 } }; const string connectionString = @"server=(localdb)\MSSQLLocalDB;Initial Catalog=StockMarketDb;Integrated Security=True;"; var factory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2012 .ConnectionString(connectionString).ShowSql()) .Mappings(m => m.FluentMappings .Add <CompanyNhibernateMap>() .Add <StockQuoteNhibernateMap>() ) .ExposeConfiguration(c => SchemaMetadataUpdater.QuoteTableAndColumns(c)) .BuildSessionFactory(); var session = factory.OpenSession(); session.Save(stock); session.Flush(); }
public ISessionFactory GetSessionFactory() { Configuration cfg = ConfigureNHibernateFromConfigFile(); // OR ConfigureNHibernate (); HbmMapping mapping = GetMappings(); cfg.AddDeserializedMapping(mapping, "BackendDotNet.Library.Schema"); SchemaMetadataUpdater.QuoteTableAndColumns(cfg); ISessionFactory sessionFactory = cfg.BuildSessionFactory(); return(sessionFactory); }
public static void Setup() { myConfiguration = NhiberanteConfigure(); HbmMapping mapping = GetMappings(); myConfiguration.AddDeserializedMapping(mapping, "NHSchema"); SchemaMetadataUpdater.QuoteTableAndColumns(myConfiguration); mySessionFactory = myConfiguration.BuildSessionFactory(); OpenSession(); }
private void SetMappings(NHibernate.Cfg.Configuration configuration) { var mapper = new ModelMapper(); mapper.AddMappings(MappingExtensions.GetMappingsAssembly <TDbContext>().GetTypes()); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mappings); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, new MsSql2012Dialect()); }
private static void BuildSchema(Configuration config) { SchemaMetadataUpdater.QuoteTableAndColumns(config); var update = new SchemaUpdate(config); update.Execute(false, true); // TODO Wait for FluentMigrator.NHibernate to become more stable // (or switch back to internal migrations entirely) //RunMigrations (); }
public static void ApplySchemaChanges() { Configuration cfg = GetConfiguration(); SchemaMetadataUpdater.QuoteTableAndColumns(cfg); //NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg); //schema.Create(false, true); var update = new SchemaUpdate(cfg); update.Execute(true, true); }
private static void SetMappings(Configuration configuration) { var mapper = new ModelMapper(); mapper.AddMappings(typeof(User).Assembly.GetTypes()); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddMapping(mappings); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, new SQLiteDialect()); }