Fluent configuration API for NHibernate
Ejemplo n.º 1
0
 static void setupTestConfig(ref FluentConfiguration pConfig, ref ISessionFactory pFactory)
 {
     pConfig = FluentNHibernate.Cfg.Fluently.Configure().Database(
        MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("GotHoursTestConStr")
        ).ShowSql()).Mappings(m => m.FluentMappings.AddFromAssemblyOf<GotHoursDAL.Mappings.TaskMap>());
     pFactory = _config.BuildSessionFactory();
 }
        public SessionSource(FluentConfiguration config)
        {
            configuration = config.Configuration;

            sessionFactory = config.BuildSessionFactory();
            dialect = Dialect.GetDialect(configuration.Properties);
        }
        private static void CreateConfiguration()
        {

            configuration = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("db")))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<OrderType>()).ExposeConfiguration(f => f.SetInterceptor(new SqlStatementInterceptor()));
        }
Ejemplo n.º 4
0
        public static ISessionFactory GetSessionFactory(NhDataContext context, FluentConfiguration factoryConfig, AutoPersistenceModel autoPersistanceModel = null)
        {
            var contextType = context.GetType();
            var contextAssembly = Assembly.GetAssembly(contextType);

            return _factories.GetOrAdd(contextType, CreateSessionFactory(contextAssembly, factoryConfig, autoPersistanceModel));
        }
        private static void UpdateDatabaseSchemaUsing(FluentConfiguration fluentConfiguration)
        {
            var configuration = fluentConfiguration.BuildConfiguration();

            new SchemaUpdate(configuration)
                .Execute(false, true);
        }
        public override void PreInitialize(IAbpInitializationContext initializationContext)
        {
            base.PreInitialize(initializationContext);

            NHibernateUnitOfWorkRegistrer.Initialize(initializationContext);
            Configuration = Fluently.Configure();
        }
Ejemplo n.º 7
0
 protected virtual FluentConfiguration DoMappingsFromAssembly(FluentConfiguration fluentConfig)
 {
     return fluentConfig
         .Mappings(x =>
         {
             x.FluentMappings.AddFromAssemblyOf<JackWeb.Data.Collectors.FacebookCollector>();
         });
 }
Ejemplo n.º 8
0
        static void CreateDatabaseWhenDebug(FluentConfiguration configuration)
        {
#if DEBUG
            if (configuration == null) throw new ArgumentNullException("configuration");
            configuration.ExposeConfiguration(
                config => new SchemaUpdate(config).Execute(false, true));
#endif
        }
 public void AddAvailableMappings(FluentConfiguration fluentConfiguration)
 {
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<PagePropertiesMap>());
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<PageMap>());
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<MediaMap>());
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<BlogPostMap>());
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<RoleMap>());
     fluentConfiguration.Mappings(mc => mc.FluentMappings.AddFromAssemblyOf<SubscriberMap>());
 }
 public ISessionFactory InitSessionFactory()
 {
     _fluentConfiguration = Fluently.Configure()
         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<PizzaMap>())
         .Database(MsSqlConfiguration.MsSql2008.ShowSql()
                   .IsolationLevel("ReadCommitted")
                   .ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString"))
                   .ShowSql());
     return _fluentConfiguration.BuildSessionFactory();
 }
        private static void ConnectWithSqlServer2008(FluentConfiguration config)
        {
            config.Database(

                MsSqlConfiguration.MsSql2008
                    .ConnectionString(c => c.FromConnectionStringWithKey("DbConnection"))
                    .ShowSql()
                    ).Cache(c =>
                    c.UseQueryCache().ProviderClass<HashtableCacheProvider>());
        }
Ejemplo n.º 12
0
 private void ConfigureForMSSQL(FluentConfiguration configuration)
 {
     configuration.Database(MsSqlConfiguration.MsSql2005
                                .ConnectionString("Data Source=gor-laptop;Initial Catalog=NHibernateSandbox;Persist Security Info=True;User ID=sa;Password=sa123456;Asynchronous Processing=true;MultipleActiveResultSets=True")
                                .Dialect(typeof (NHibernate.Dialect.MsSql2005Dialect).AssemblyQualifiedName)
                                .Driver(typeof(NHibernate.Driver.SqlClientDriver).AssemblyQualifiedName)
                                .FormatSql()
                                .ShowSql()
                                );
 }
Ejemplo n.º 13
0
 public static Fluently Using(Assembly asm)
 {
     lock (syncRoot)
     {
         currentFluentConfig = FluentNHibernate.Cfg.Fluently
            .Configure()
            .Mappings(m => m.FluentMappings.AddFromAssembly(asm));
         //
         return new Fluently(currentFluentConfig);
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Create database structure from entities
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public static void Export(FluentConfiguration configuration)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");

            Configuration config = null;
            configuration.ExposeConfiguration(c => config = c);
            var factory = configuration.BuildSessionFactory();

            var export = new SchemaExport(config);
            export.Execute(false, true, false, factory.OpenSession().Connection, null);
        }
 private void InitMapping(FluentConfiguration fluentConfiguration)
 {
     fluentConfiguration.Mappings(
         x =>
             {
                 x.AutoMappings.Add(Generate());
     #if DEBUG
                 x.AutoMappings.ExportTo(@"D:\Temp");
     #endif
             });
 }
Ejemplo n.º 16
0
        public ISessionFactory GetSessionFactory()
        {
            if (_sessionFactory == null)
            {
                _fluentConfiguration = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString")))
                    //.Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Livro>(new AppAutomappingCfg())));
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<AutorMap>());

                _sessionFactory = _fluentConfiguration.BuildSessionFactory();
            }

            return _sessionFactory;
        }
Ejemplo n.º 17
0
 /*public ISessionFactory Session
 {
     get
     {
         session = fluentCfg.BuildSessionFactory();
         return session;
     }
 }*/
 public DatabaseConfiguration()
 {
     Encrypter encrypter = new Encrypter("64bit");
     string keyword = encrypter.Decrypt("QnV0IHlvdSBkb24ndCByZWFsbHkgbWVhbiBpdA==");
     encrypter.SetCrypter("AES");
     this.connectionString = encrypter.Decrypt("Sf+ulELX4tNuvsQtUG2EZWPJDPhm8obnrSyEm7F5mtg/eziYSjoIZndeCHk8iZOhvAuMNJBxiiatrRHTt2LVFv/vJNoo8yCHkOO7TwUWv3+l8+Wpis4TSsEvc8zHgEPIucH/OQ2tyYlMboyoFH26dZLZ2Y+Kevfu79VfqLBcKGE=", keyword);
     fluentCfg = Fluently.Configure().Database(PostgreSQLConfiguration.Standard.ConnectionString(this.connectionString)).Mappings(m =>
     {
         m.HbmMappings.AddFromAssemblyOf<Users>();
         m.HbmMappings.AddFromAssemblyOf<Contacts>();
     });
     var config = fluentCfg.BuildSessionFactory();
 }
        private static void ApplyDefaultsTo(FluentConfiguration fluentConfiguration)
        {
            fluentConfiguration.ExposeConfiguration(
                c =>
                    {
                        c.SetProperty("current_session_context_class",typeof(ThreadStaticSessionContext).AssemblyQualifiedName);

                        //default to LinFu if not specifed by user
                        if (!c.Properties.Keys.Contains(PROXY_FACTORY_KEY))
                            c.SetProperty(PROXY_FACTORY_KEY,typeof(ProxyFactoryFactory).AssemblyQualifiedName);
                    }
                );
        }
 public FluentConfiguration Configure()
 {
     return Config ?? (Config =
         Fluently.Configure()
         // Bug fix: http://stackoverflow.com/questions/2361730/assertionfailure-null-identifier-fluentnh-sqlserverce
         .ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close"))
         .Database(
             MsSqlCeConfiguration.Standard
             .ConnectionString(string.Format("Data Source={0};", DatabaseFilename))
             .ShowSql()
         )
     );
 }
Ejemplo n.º 20
0
        public BootStrap()
        {
            _userName = "******";
            _password = "******";
            DbFile = "test.db";
            ConnectionString = String.Format("ServerType=1;User={0};Password={1};Dialect=3;Database={2}", _userName, _password, DbFile);

            //setup firebird configuration
            firebird = new FirebirdConfiguration();
            firebirdConfig = Fluently.Configure().Database(
                     firebird.ConnectionString(c => c
                     .Is(ConnectionString)));
        }
Ejemplo n.º 21
0
 private void CreateNHibernateFactory()
 {
     string connectionString = ConfigurationManager.ConnectionStrings["SqlExpress"].ConnectionString;
     Config = Fluently.Configure()
     .Database(MsSqlConfiguration.MsSql2008
                   .ConnectionString(connectionString))
     .Mappings(m =>
               m.FluentMappings.AddFromAssemblyOf<Log>())
     .ExposeConfiguration(
         c => c.SetProperty("current_session_context_class", "web"));
      //create session factory
      SessionFactory = Config.BuildSessionFactory();
 }
Ejemplo n.º 22
0
		public static ISessionFactory BuildSessionFactory(FluentConfiguration config) {

			try {
				return config.BuildSessionFactory();
			} catch (ArgumentException x) {
				log.FatalException("Error while building session factory", x);
				throw;
			} catch (FluentConfigurationException x) {
				log.FatalException("Error while building session factory", x);
				throw;
			}

		}
Ejemplo n.º 23
0
        public static void Config()
        {
            _configuration = Fluently
                .Configure()
                .Database(MsSqlConfiguration
                              .MsSql2008
                              .ConnectionString(x => x.FromConnectionStringWithKey("local")))
                .Mappings(config => config.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));

            var export = new SchemaUpdate(_configuration.BuildConfiguration());
            export.Execute(true, true);

            _sessionFactory = _configuration.BuildSessionFactory();
        }
Ejemplo n.º 24
0
        public static void Load()
        {
            _config = Fluently.Configure();

            if (Manager.Settings.Driver == Settings.DbDriver.Sqlite)
            {
                var dbfile = Path.Combine(Manager.Settings.BasePath, Manager.Settings.SqliteFile);
                var basepath = Path.GetDirectoryName(dbfile);
                if (basepath != null && !Directory.Exists(basepath))
                {
                    try
                    {
                        Directory.CreateDirectory(basepath);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(String.Format("Could not create directory {0}: {1}", basepath, ex.Message),
                            Logger.LogType.Error, typeof (SessionFactory));
                    }
                }
                Logger.Log(String.Format("Opening Database {0}", dbfile), Logger.LogType.Info, typeof (SessionFactory));

                var sqlcfg = SQLiteConfiguration.Standard.UsingFile(dbfile);
                //sqlcfg.ShowSql();
                //sqlcfg.FormatSql();
                _config.Database(sqlcfg);
            }
            if (Manager.Settings.Driver == Settings.DbDriver.Mysql)
            {
                var sqlcfg = MySQLConfiguration.Standard.ConnectionString(
                    String.Format(
                        "Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                        Manager.Settings.MysqlHost,
                        Manager.Settings.MysqlPort,
                        Manager.Settings.MysqlDatabase,
                        Manager.Settings.MysqlUser,
                        Manager.Settings.MysqlPassword
                        ));
                sqlcfg.Dialect<MySQL55InnoDBDialect>();
                //sqlcfg.ShowSql();
                //sqlcfg.FormatSql();
                _config.Database(sqlcfg);
            }
            _config.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Vehicle>());
            _factory = _config.BuildSessionFactory();
            #if DEBUG
            //BuildSchema();
            #endif
        }
        public FluentConfiguration BuildMapping(FluentConfiguration configuration, Type type, string nameSpace)
        {
            configuration = configuration
               .Mappings(m =>
               {
                   m.AutoMappings.Add(
                       AutoMap.Assemblies(Assembly.GetAssembly(type))
                       .UseOverridesFromAssembly(Assembly.GetAssembly(type))
                       .Conventions.AddAssembly(Assembly.GetAssembly(type))
                       .Where(t => t.Namespace != null && t.Namespace.StartsWith(nameSpace)));
                   m.HbmMappings.AddFromAssembly(Assembly.GetAssembly(type)); // for stored procedures
               });

            return configuration;
        }
Ejemplo n.º 26
0
        public NHibernateDatabaseTest()
        {
            if (Configuration == null)
            {

                Configuration = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(ConfigurationManager.ConnectionStrings["Default"].ConnectionString).ShowSql())
                    .Mappings(m =>
                              m.FluentMappings.AddFromAssemblyOf<EmployeeMap>())
                               .Mappings(m => m.HbmMappings.AddClasses(typeof(CandidateMap)));

                SessionFactory = Configuration.BuildSessionFactory();
            }

             session = SessionFactory.OpenSession();
        }
Ejemplo n.º 27
0
 public static ISessionFactory Create(FluentConfiguration fluentConfiguration, DatabaseConfiguration databaseConfiguration) {
     var sessionFactory = fluentConfiguration
         .Database(MsSqlConfiguration.MsSql2005
             .ConnectionString(c => c
                 .Database(databaseConfiguration.DatabaseName)
                 .Server(databaseConfiguration.ServerName)
                 .TrustedConnection())
             .ShowSql())
         .ExposeConfiguration(configuration => {
             if (databaseConfiguration.CreateDatabase) {
                 new SchemaExport(configuration).Create(true, true);
             }
         })
         .BuildSessionFactory();
     return sessionFactory;
 }
Ejemplo n.º 28
0
        public static void ConfigureAutoMapping()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.SetNamingStrategy(DefaultNamingStrategy.Instance);

            FluentNHibernate.Cfg.FluentConfiguration fConfig = FluentNHibernate.Cfg.Fluently.Configure(config);
            var sessionFactory = Fluently.Configure(config)
                                 .Database(MsSqlConfiguration.MsSql2012.ConnectionString(new Action <ConnectionStringBuilder>(GenerateConnStr)))
                                 .ExposeConfiguration(BuildSchema)
                                 .Mappings(m =>
                                           m.AutoMappings
                                           .Add(AutoMap.AssemblyOf <Product>()))
                                 .BuildSessionFactory();

            var k = sessionFactory.OpenSession();
        }
        public DataConfiguration(string databaseFile)
        {
            NHibernateProfiler.Initialize();
            _fluentConfiguration = Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard
                        .UsingFile(databaseFile)
                        .AdoNetBatchSize(16)
                )
                .Mappings(m => m.AutoMappings.Add(AutoMap
                                                      .AssemblyOf<Casa>().Where(c => c.Namespace.EndsWith("Entities"))
                                                      .Conventions.AddFromAssemblyOf<CascadeConvention>()
                                                      .UseOverridesFromAssemblyOf<CasaOverride>()));

            _configuration = _fluentConfiguration
                .BuildConfiguration();
        }
Ejemplo n.º 30
0
 private void InitializeFluentConfiguration()
 {
     fluentConfiguration = Fluently
         .Configure()
         .Database(MsSqlConfiguration.MsSql2008
             .ConnectionString(connectionString))
             //.CurrentSessionContext("web")
             //.ProxyFactoryFactory(typeof (ProxyFactoryFactory).AssemblyQualifiedName))
         .Mappings(m => m.AutoMappings.Add(AutoMap
             .AssemblyOf<Entity>(new AutoMappingConfiguration())
             .UseOverridesFromAssemblyOf<Entity>()
             .Conventions.Add(
                 ForeignKey.EndsWith(DatabaseConstants.IdentitySuffix),
                 Table.Is(x => x.EntityType.Name.Pluralize()),
                 OptimisticLock.Is(x => x.Version()),
                 new DiscriminatorConvention())));
 }
 public void AddAvailableMappings(FluentConfiguration fluentConfiguration)
 {
     foreach (var module in modulesRegistry.GetModules())
     {
         try
         {
             var assembly = assemblyLoader.Load(module.ModuleDescriptor.AssemblyName);
             if (assembly != null)
             {
                 fluentConfiguration = fluentConfiguration.Mappings(m => m.FluentMappings.AddFromAssembly(assembly));
             }
         }
         catch (Exception ex)
         {
             Logger.ErrorFormat("Failed to load mappings from module {0} (assembly {1}).", ex, module.ModuleDescriptor.Name, module.ModuleDescriptor.AssemblyName);
         }
     }
 }
Ejemplo n.º 32
0
        public static ISessionFactory CreateSessionFactory(string portalServer, string portalDatabase)
        {
            FluentNHibernate.Cfg.FluentConfiguration config = Fluently.Configure()
                                                              .Database(PostgreSQLConfiguration.Standard
                                                                        .ConnectionString(c => c
                                                                                          .Host(portalServer) //202.4.229.96
                                                                                          .Port(5432)
                                                                                          .Database(portalDatabase)
                                                                                          .Username("ofp_admin")
                                                                                          .Password("ofp_admin")))
                                                              .Mappings(m => m.FluentMappings.AddFromAssemblyOf <IMS.DAL.Maps.Ves.VesselCategoriesMap>());

            //.ExposeConfiguration(con =>
            //    {
            //        con.SetProperty("adonet.batch_size", "1");
            //    })

            return(config.BuildSessionFactory());
        }