public static Configuration GetConfiguration()
        {
            FluentConfiguration fluentConfig = Fluently.Configure()
                                               .Database(
                MsSqlConfiguration.MsSql2008.Dialect <MsSql2008Dialect>()
                //SQLiteConfiguration.Standard.Dialect<SQLiteDialect>()
                .ConnectionString(x => x.FromConnectionStringWithKey("CheatSheets"))
                )
                                               .ProxyFactoryFactory <ProxyFactoryFactory>()
                                               .Mappings(m => {
                m.FluentMappings.AddFromAssemblyOf <NHibernateConfigurator>();
                m.AutoMappings.Add(
                    AutoMap
                    .AssemblyOf <Entity>().Where(type => !type.IsAbstract && typeof(Entity).IsAssignableFrom(type))
                    .Conventions.AddFromAssemblyOf <NamingConvention>()
                    .Conventions.Add(
                        PrimaryKey.Name.Is(x => "ID"),
                        DefaultLazy.Always(),
                        ForeignKey.Format(FormatFkName)                                         //naming for FK  columns
                        )
                    );
            })
                                               .ExposeConfiguration(config => config.Properties.Add("use_proxy_validator", "false"));

            Configuration cfg = fluentConfig.BuildConfiguration();

            cfg.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] {
                new NHibernateAuditSaveListener()
            };
            cfg.EventListeners.SaveOrUpdateEventListeners = new ISaveOrUpdateEventListener[] {
                new NHibernateAuditSaveListener()
            };

            return(cfg);
        }
Exemple #2
0
        public void InitializeFactory()
        {
            if (!_isInitialized)
            {
                FluentConfiguration conf = Fluently.Configure()
                                           .Database(MySQLConfiguration.Standard.ConnectionString(_connection))
                                           .CurrentSessionContext <ThreadLocalSessionContext>()
                                           .Mappings(map =>
                {
                    map.FluentMappings.Conventions.Add(
                        new EnumConvention(),
                        new CascadeAllConvention(),
                        new ColumnNameConvention(),
                        new TableNameConvention(),
                        LazyLoad.Never()
                        );
                    map.FluentMappings.AddFromAssemblyOf <EmployeeMap>();
                })
                                           .ExposeConfiguration(x =>
                {
                    x.SetInterceptor(new SqlStatementInterceptor());
                    x.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new EntityService() };
                });

                if (!_writeOnly)
                {
                    conf.ExposeConfiguration(config => new SchemaUpdate(conf.BuildConfiguration()).Execute(true, true));
                }

                _sessionFactory = conf.BuildSessionFactory();

                _isInitialized = true;
            }
        }
        public Configuration GetConfiguration()
        {
            var NHibernateAssembly = Assembly.Load("Naftan.Maintenance.NHibernate");
            var DomainAssembly     = Assembly.Load("Naftan.Maintenance.Domain");
            var CommonAssembly     = Assembly.Load("Naftan.Common");

            var msSqlDatabase = MsSqlConfiguration.MsSql2008
                                .UseOuterJoin()
                                .ShowSql()
                                .FormatSql()
                                // !!!ВНИМАНИЕ Аккуратнее с настойками базы данных для тестов. Если указать рабочую(боевую) базу данных, то ВСЕ РАБОЧИЕ ДАННЫЕ БУДУТ УДАЛЕНЫ !!!
                                .ConnectionString("data source = db2; initial catalog = maintenance_test; integrated security = SSPI;")
                                .UseReflectionOptimizer()
                                .AdoNetBatchSize(100);

            var automapping = AutoMap.Assemblies(new AutomappingConfig(), CommonAssembly, DomainAssembly)
                              .Conventions.AddAssembly(CommonAssembly)
                              .AddMappingsFromAssembly(NHibernateAssembly)
                              .UseOverridesFromAssembly(NHibernateAssembly);

            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(msSqlDatabase)
                                      .Mappings(x => x.AutoMappings.Add(automapping)
                                                );

            var configuration = cfg.BuildConfiguration();

            return(configuration);
        }
Exemple #4
0
        public ISessionFactory GetFactory()
        {
            if (factory == null)
            {
                Assembly assembly = GetAssembly();
                DbConnectionStringBuilder connStringBuilder = GetConnectionStringBuilder();
                FluentConfiguration       configuration     = Fluently.Configure()
                                                              .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connStringBuilder.ConnectionString).ShowSql())
                                                              .Mappings(m => m.FluentMappings.AddFromAssembly(assembly));

                if (createSchema)
                {
                    SchemaUpdate(connStringBuilder, configuration.BuildConfiguration());
                }

                factory = configuration.BuildSessionFactory();

                if (factory == null)
                {
                    throw new InvalidOperationException("BuildSessionFactory is null.");
                }
            }

            return(factory);
        }
        private static void UpdateDatabaseSchemaUsing(FluentConfiguration fluentConfiguration)
        {
            var configuration = fluentConfiguration.BuildConfiguration();

            new SchemaUpdate(configuration)
            .Execute(false, true);
        }
Exemple #6
0
        /// <summary>
        /// Only development phase usage do not use production code
        /// </summary>
        /// <param name="factoryKey"></param>
        private void BuildSchemaByDroping(string factoryKey)
        {
            var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, factoryKey + ".NHibernate.config")?.FirstOrDefault();

            if (string.IsNullOrEmpty(filePath))
            {
                Console.WriteLine(factoryKey + ".NHibernate.config file not found for BuildSchemaDroping!");
                return;
            }
            var nHibernateMappingAssembly = GetAssemblyName(filePath);

            var cfg = new global::NHibernate.Cfg.Configuration();

            cfg.Configure(filePath);
            FluentConfiguration a = Fluently.Configure(cfg).Mappings(m =>
            {
                var assembly = Assembly.Load(nHibernateMappingAssembly);
                m.HbmMappings.AddFromAssembly(assembly);
                m.FluentMappings.AddFromAssembly(assembly).Conventions.AddAssembly(assembly);
            });

            SchemaExport schema = new SchemaExport(a.BuildConfiguration());

            if (schema != null)
            {
                schema.Execute(true, true, false);
            }
        }
Exemple #7
0
        private ISessionFactory CreateSessionFactory()
        {
            FluentConfiguration fluentConfiguration = Fluently.Configure();

            IPersistenceConfigurer sqlConfiguration = CreateSqlConfiguration();

            if (sqlConfiguration != null)
            {
                fluentConfiguration = fluentConfiguration.Database(sqlConfiguration);
            }

            mappingResolver.AddAvailableMappings(fluentConfiguration);

            var eventListenerHelper       = new EventListenerHelper(securityService);
            var saveOrUpdateEventListener = new SaveOrUpdateEventListener(eventListenerHelper);
            var deleteEventListener       = new DeleteEventListener(eventListenerHelper);

            fluentConfiguration = fluentConfiguration
                                  .Mappings(m => m.FluentMappings
                                            .Conventions.Add(ForeignKey.EndsWith("Id"))
                                            .Conventions.Add <EnumConvention>())
                                  .ExposeConfiguration(c => c.SetProperty("show_sql", "false"))
                                  .ExposeConfiguration(c => c.SetListener(ListenerType.Delete, deleteEventListener))
                                  .ExposeConfiguration(c => c.SetListener(ListenerType.SaveUpdate, saveOrUpdateEventListener))
                                  .ExposeConfiguration(c => c.SetListener(ListenerType.Save, saveOrUpdateEventListener))
                                  .ExposeConfiguration(c => c.SetListener(ListenerType.Update, saveOrUpdateEventListener));

            return(fluentConfiguration
                   .BuildConfiguration()
                   .BuildSessionFactory());
        }
Exemple #8
0
        public Configuration GetConfiguration()
        {
            var NHibernateAssembly = Assembly.Load("Naftan.Maintenance.NHibernate");
            var DomainAssembly     = Assembly.Load("Naftan.Maintenance.Domain");
            var CommonAssembly     = Assembly.Load("Naftan.Common");

            var msSqlDatabase = MsSqlConfiguration.MsSql2008
                                .UseOuterJoin()
                                .ConnectionString(s => s.FromConnectionStringWithKey("maintenance"))
                                .UseReflectionOptimizer()
                                .AdoNetBatchSize(100);

            var automapping = AutoMap.Assemblies(new AutomappingConfig(), CommonAssembly, DomainAssembly)
                              .Conventions.AddAssembly(CommonAssembly)
                              .AddMappingsFromAssembly(NHibernateAssembly)
                              .UseOverridesFromAssembly(NHibernateAssembly);

            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(msSqlDatabase)
                                      .Mappings(x => x.AutoMappings.Add(automapping)
                                                );

            var configuration = cfg.BuildConfiguration();

            return(configuration);
        }
        private static ISession CreateSession(this FluentConfiguration configuration)
        {
            var session = configuration.BuildSessionFactory().OpenSession();

            new SchemaExport(savedConfiguration ?? configuration.BuildConfiguration())
            .Execute(true, true, false, session.Connection, Console.Out);
            return(session);
        }
Exemple #10
0
        public void Initialize(IContainer container)
        {
            var typeDiscoverer = container.Get <ITypeDiscoverer>();

            FluentConfiguration.Mappings(m => DiscoverClassMapsAndAddAssemblies(typeDiscoverer, m));
            Configuration  = FluentConfiguration.BuildConfiguration();
            SessionFactory = Configuration.BuildSessionFactory();
        }
Exemple #11
0
        public static ISession GetInMemorySession()
        {
            var session = Factory.OpenSession();

            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
            new SchemaExport(Config.BuildConfiguration())
            .Execute(false, true, false, session.Connection, null);
            return(session);
        }
        public static CoreNHibernate.ISessionFactory CreateSessionFactory(DBTypes dbType)
        {
            FluentConfiguration config = Fluently.Configure();

            switch (dbType)
            {
            case DBTypes.Oracle:
                config = OracleHelper.ConfigurationFactory();
                break;

            case DBTypes.MSSQL:
                config = MsSqlHelper.ConfigurationFactory();
                break;

            case DBTypes.SQLite:
                config = SQLiteHelper.ConfigurationFactory();
                break;

            case DBTypes.MySQL:
            default:
                throw new NotImplementedException("Not implemented yet...");
            }

            var enversConf = new EnversNHibernate.Configuration.Fluent.FluentConfiguration();

            List <Type> domainEntities = Assembly.GetAssembly(typeof(Clients)).GetTypes() // Assembly.Load("bilisimHR.DataLayer.Core").GetTypes()
                                         .Where(t => (typeof(Entity <int>).IsAssignableFrom(t) && !t.IsGenericType))
                                         .ToList();

            foreach (Type type in domainEntities)
            {
                enversConf.Audit(type);
            }

            CoreNHibernate.Cfg.Configuration cfg = new CoreNHibernate.Cfg.Configuration();
            cfg = config.BuildConfiguration();

            cfg.BuildMappings();
            cfg.SetInterceptor(new TrackingInterceptor());

            //Envers RevType Values
            //0(ADD), 1(MODIFY) and 2(DELETE)
            ConfigurationKey.AuditTableSuffix.SetUserValue(cfg, "_LOG");
            IRevisionInfoService revInfoService = new RevisionInfoService();

            // Service Locator Registry
            ServiceLocator.RegisterService(revInfoService);
            ServiceLocator.RegisterService(new HttpRequestMessageService());

            enversConf.SetRevisionEntity <CustomRevInfo>(e => e.Id, e => e.RevisionDate, new CustomRevInfoListener());
            cfg.IntegrateWithEnvers(enversConf);

            config.ExposeConfiguration(exp => new SchemaUpdate(cfg).Execute(false, true))
            .ExposeConfiguration(c => { c.CurrentSessionContext <CoreNHibernate.Context.CallSessionContext>(); });
            //config.ExposeConfiguration(exp => new SchemaExport(cfg).Execute(true, true, false));
            return(config.BuildSessionFactory());
        }
Exemple #13
0
        private static ISessionFactory ConfigureSessionFactory()
        {
            if (ShouldRecreateDb())
            {
                CreateDatabase();
            }
            FluentConfiguration configuration = CreateNHibernateConfiguration();

            return(configuration.BuildConfiguration().BuildSessionFactory());
        }
Exemple #14
0
        public NhibernateManagerDataBase(FluentConfiguration builderConfiguration)
        {
            Guard.NotNull("fluentConfiguration", builderConfiguration);

            var configuration = builderConfiguration.BuildConfiguration();

            this.schemaExport   = new SchemaExport(configuration);
            this.schemaUpdate   = new SchemaUpdate(configuration);
            this.schemaValidate = new SchemaValidator(configuration);
        }
        public static void ConfigureIncodingNhDataServices(this IServiceCollection services,
                                                           Type entityType, string path,
                                                           Func <FluentConfiguration, FluentConfiguration> builderConfigure)
        {
            services.AddSingleton <IUnitOfWorkFactory, NhibernateUnitOfWorkFactory>();

//            string path = Path.Combine(AppContext.BaseDirectory, string.Format("fluently_{0}_{1}.cfg", version,
//#if DEBUG
//                new string(connectionString.ToCharArray().Select(r => Char.IsLetterOrDigit(r) ? r : 'a').ToArray())
//#else
//                ""
//#endif
//            ));

            Func <Configuration> config = () =>
            {
                FluentConfiguration fluently = Fluently.Configure();
                fluently = builderConfigure(fluently);
                fluently = fluently
                           .Mappings(configuration => configuration.FluentMappings
                                     .Add(typeof(DelayToSchedulerNhMap))
                                     .AddFromAssembly(entityType.Assembly));

                return(fluently.BuildConfiguration());
            };

            //var dbContext = FileCaching.Evaluate(path, () =>
            //{
            //Func<string, IncDbContext> incDbContext = (cs) =>
            //{
            //    var dbContextOptionsBuilder = new DbContextOptionsBuilder<IncDbContext>();
            //    builderConfigure(dbContextOptionsBuilder);
            //    return new IncDbContext(dbContextOptionsBuilder.Options, entityType.Assembly);
            //};
            //    return incDbContext;
            //});
            //incDbContext(connectionString).Database.EnsureCreated();
            NhibernateSessionFactory sessionFactory = new NhibernateSessionFactory(config, path);

            services.AddSingleton <INhibernateSessionFactory>(sessionFactory);

            //var container = new Container();
            //container.Register<IDispatcher, DefaultDispatcher>();

            //container.Register<IUnitOfWorkFactory, NhibernateUnitOfWorkFactory>(Lifestyle.Singleton);

            //Configuration cfg = NhibernatePersist.CreateDefault(entityType, connectionString, version);

            //container.RegisterSingleton<INhibernateSessionFactory>(() =>
            //{
            //    FluentConfiguration configure = Fluently.Configure(cfg);
            //    return new NhibernateSessionFactory(configure);
            //});
            //container.Register<IUnitOfWorkFactory, NhibernateUnitOfWorkFactory>(Lifestyle.Singleton);
        }
Exemple #16
0
 public static void BuildSchema()
 {
     try
     {
         new SchemaExport(_config.BuildConfiguration()).Create(false, true);
     }
     catch (Exception ex)
     {
         Logger.Log(ex.Message, Logger.LogType.Error, typeof(SessionFactory));
     }
 }
Exemple #17
0
        private static void UpdateDatabaseSchemaUsing(FluentConfiguration fluentConfiguration, ISessionFactory factory)
        {
            var configuration = fluentConfiguration.BuildConfiguration();

            using (var session = factory.OpenSession())
            {
                var export = new SchemaExport(configuration);
                export.Execute(true, true, false, session.Connection, null);
                session.Flush();
            }
        }
Exemple #18
0
        public static void BuildSchema()
        {
            CreateDatabaseDirectoryIfNotExist();
            if (DatabaseExists)
            {
                DropDatabase();
            }

            new SchemaExport(_configuration.BuildConfiguration())
            .Create(false, true);
        }
Exemple #19
0
        public void ValidateSchema()
        {
            SchemaValidator validator = new SchemaValidator(_fluentConfiguration.BuildConfiguration());

            validator.Validate();
            try
            {
            }
            catch (HibernateException ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
 public void SetupDb(Assembly migrationAssembly = null)
 {
     SqlCeDbHelper.CreateDatabaseFile(DatabaseFilename);
     if (migrationAssembly == null)
     {
         new SchemaExport(Config.BuildConfiguration()).Execute(true, true, false);
     }
     else
     {
         var migrator = new Migrator.Migrator("SqlServerCE", "Data Source=" + DatabaseFilename, migrationAssembly, true);
         migrator.MigrateToLastVersion();
     }
 }
Exemple #21
0
        static ISessionFactory CreateNHibernateSessionFactory()
        {
            FluentConfiguration fc = Fluently.Configure()
                                     .Database(MsSqlConfiguration.MsSql2012.ConnectionString("Server=.\\SQLEXPRESS;Database=NHibernateTests;Trusted_Connection=True;"))
                                     .Mappings(m => {
                m.FluentMappings
                .AddFromAssembly(Assembly.GetExecutingAssembly());
            });
            var config = fc.BuildConfiguration();

            return(config.SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, "on_close")
                   .BuildSessionFactory());
        }
 public static void MappingTablenames(FluentConfiguration cfg, Type t, string newtablename = "")
 {
     if (newtablename == "")
     {
         return;
     }
     foreach (PersistentClass persistClass in cfg.BuildConfiguration().ClassMappings)
     {
         if (persistClass.MappedClass == t)
         {
             persistClass.Table.Name = newtablename;
         }
     }
 }
        public Configuration GetConfiguration()
        {
            SQLiteConfiguration persistenceConfigurer = SQLiteConfiguration.Standard
                                                        .Dialect <MySQLiteDialect>()
                                                        .InMemory()
                                                        .ShowSql();

            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(persistenceConfigurer)
                                      .ExposeConfiguration(ExtendConfiguration)
                                      .ProxyFactoryFactory <DefaultProxyFactoryFactory>()
                                      .Mappings(mappings);

            return(cfg.BuildConfiguration());
        }
        /// <summary>
        /// Пооверить структуру таблиц.
        /// </summary>
        /// <returns></returns>
        public virtual DbContext ValidateSchema()
        {
            try
            {
                FluentConfiguration  dbConfig = Configure();
                NH.Cfg.Configuration config   = dbConfig.BuildConfiguration();
                var schema = new SchemaValidator(config);
                schema.Validate();

                return(new DbContext(this, dbConfig.BuildSessionFactory()));
            }
            catch (Exception ex)
            {
                throw new DatabaseException($"Некорректная структура таблиц БД: {this}.", ex);
            }
        }
        public Configuration GetConfiguration()
        {
            MsSqlConfiguration config = MsSqlConfiguration.MsSql2008
                                        .ConnectionString(x => x.FromConnectionStringWithKey("Main"))
                                        .UseReflectionOptimizer()
                                        .AdoNetBatchSize(100);

            FluentConfiguration fluentConfiguration = Fluently.Configure()
                                                      .CurrentSessionContext <ThreadStaticSessionContext>()
                                                      .Database(config)
                                                      .Mappings(x => x.FluentMappings.AddFromAssemblyOf <LjuserMap>()
                                                                .Conventions.AddFromAssemblyOf <TableNameConvention>())
                                                      .ExposeConfiguration(c => c.SetProperty("generate_statistics", "true")
                                                                           .SetProperty("adonet.batch_size", "100"));

            return(fluentConfiguration
                   .BuildConfiguration());
        }
Exemple #26
0
            public void Regist(bool buildHbmFile, string exportHbmFolder)
            {
                IEnumerable <Assembly> fluentAssemblies = GetFluenAssembly();
                IEnumerable <Assembly> nhAssembilies    = GetHbmXmlFile();

                foreach (Type type in _regType.Keys)
                {
                    OrnamentContext.DaoFactory.Regist(type, _regType[type]);
                }
                SessionManager.Regist("default", () =>
                {
                    var config            = new Configuration();
                    string configFileName = ConfigurationManager.AppSettings["nhConfig"];
                    if (String.IsNullOrEmpty(configFileName))
                    {
                        throw new ArgumentNullException(
                            "nhConfig section can't be find in the config file. please set it up in the appSettiong section.");
                    }
                    config.Configure(ApplicationHelper.MapPath(configFileName));
                    FluentConfiguration result = Fluently.Configure(config);


                    foreach (Assembly assembly in fluentAssemblies)
                    {
                        if (buildHbmFile)
                        {
                            Assembly assembly1 = assembly;
                            result.Mappings(s => s.FluentMappings.AddFromAssembly(assembly1)
                                            .ExportTo(exportHbmFolder));
                        }
                        else
                        {
                            result.Mappings(s => s.FluentMappings.AddFromAssembly(assembly));
                        }
                    }

                    foreach (Assembly assembly in nhAssembilies)
                    {
                        result.Mappings(s => s.HbmMappings.AddFromAssembly(assembly));
                    }

                    return(result.BuildConfiguration());
                });
            }
        private void Boot_PreInitModules(object sender, BootstrapperEventArgs e)
        {
            string connectionStr       = ConfigurationManager.ConnectionStrings["MsSql"].ConnectionString;
            FluentConfiguration config = Fluently.Configure();

            foreach (Nefarian.Configuration.ModuleConfiguration module in e.Configuration.Modules)
            {
                config.Mappings(x => x.FluentMappings.AddFromAssembly(module.ModuleType.Assembly));
            }
            //config.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008.ConnectionString(connectionStr));
            config.Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard.ConnectionString(connectionStr));

            config.CurrentSessionContext("wcf_operation");
            ISessionFactory sessionFactory;
            bool            debugSQL = true;

            bool.TryParse(ConfigurationManager.AppSettings["DebugSQL"], out debugSQL);
            if (debugSQL)
            {
                NHibernate.Cfg.Configuration nhibernateConfig = config.BuildConfiguration();
                nhibernateConfig.Properties["show_sql"]   = "true";
                nhibernateConfig.Properties["format_sql"] = "true";
                sessionFactory = nhibernateConfig.BuildSessionFactory();
            }
            else
            {
                sessionFactory = config.BuildSessionFactory();
            }
            IUnityContainer appContainer = Nefarian.Core.WebServiceSite.GetAppContainer();

            appContainer.RegisterInstance <ISessionFactory>("Lilac", sessionFactory);
            ExchangeCenter exchange = new ExchangeCenter();

            appContainer.RegisterInstance <ExchangeCenter>(exchange);

            MessagePublisher publisher = new MessagePublisher();

            appContainer.RegisterInstance <MessagePublisher>(publisher);

            log4net.Config.XmlConfigurator.Configure();
            ILog log = LogManager.GetLogger("Lilac");

            appContainer.RegisterInstance <ILog>(log);
        }
Exemple #28
0
        private ISessionFactory CreateSessionFactory()
        {
            Configuration initialConfiguration = this.GetConfiguration()
                                                 .OrFail(nameof(this.GetConfiguration) + "()");

            FluentConfiguration fluentConfiguration = Fluently.Configure(initialConfiguration)
                                                      //.CurrentSessionContext<CurrentSessionContext>()
                                                      //.Mappings(
                                                      //    m => m.FluentMappings
                                                      //          .Add<GusContractorSnapshot.Map>()
                                                      //          .Add<GusContractorLog.Map>()
                                                      //)
            ;

            Library[] libraries = this.Librarian.OrFail(nameof(this.Librarian))
                                  .GetLibraries();

            IConvention[] conventions = this.GetConventions()
                                        .OrFail(nameof(this.Conventions));

            Type[] entities = this.GetEntities()
                              .ToArray();

            var automappingConfiguration = new AutomappingConfiguration(entities);

            foreach (Library library in libraries)
            {
                Assembly             assembly         = library.GetAssembly();
                AutoPersistenceModel assemblyMappings = AutoMap.Assembly(assembly, automappingConfiguration);
                assemblyMappings.Conventions.Add(conventions);
                assemblyMappings.UseOverridesFromAssembly(assembly);
                assemblyMappings.IgnoreBase <Entity>();

                fluentConfiguration.Mappings(m =>
                {
                    m.FluentMappings.Conventions.Add(conventions);
                    m.AutoMappings.Add(assemblyMappings);
                });
            }

            this.configuration = fluentConfiguration.BuildConfiguration();
            return(fluentConfiguration.BuildSessionFactory());
        }
Exemple #29
0
        /// <summary>
        /// Método privado estático encargado de la configuración de nHibernate con Fluent.
        /// </summary>
        /// <param name="nHibernateConfigFile">
        /// Parámetro que indica la ruta del fichero de configuración de nhibernate.
        /// </param>
        /// <param name="mappingAssemblies">
        /// Parámetro que indica la lista de ensamblados a mapear.
        /// </param>
        /// <returns>
        /// Devuelve la configuración <see cref="Configuration"/> correspondiente.
        /// </returns>
        private static Configuration FluentlyConfigureNHiberante(List <Assembly> mappingAssemblies)
        {
            // Configuramos Fluent.
            FluentConfiguration fluentConfiguration = Fluently.Configure(new Configuration().Configure());

            fluentConfiguration.Mappings(m =>
            {
                m.FluentMappings.Conventions.AddAssembly(typeof(Configurator).Assembly);

                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.FluentMappings.Conventions.AddAssembly(mappingAssembly);
                }
            })
            .Mappings(m =>
            {
                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.FluentMappings.AddFromAssembly(mappingAssembly);
                }
            })
            .Mappings(m =>
            {
                foreach (Assembly mappingAssembly in mappingAssemblies)
                {
                    m.HbmMappings.AddFromAssembly(mappingAssembly);
                }
            });

            // Añadimos configuraciones.
            fluentConfiguration.ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.BatchSize, "100"))
            .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseProxyValidator, "true"));

            PropertyInfo pinfo = typeof(FluentConfiguration).GetProperty("Configuration", BindingFlags.Instance | BindingFlags.NonPublic);

            nhConfiguration = pinfo.GetValue(fluentConfiguration, null) as Configuration;

            Configuration builtConfiguration = fluentConfiguration.BuildConfiguration();

            // Devolvemos la respuesta.
            return(builtConfiguration);
        }
        private ISessionFactory BuildSessionFactory()
        {
            Assembly            currentAssembly = Assembly.GetAssembly(this.GetType());
            FluentConfiguration fc = Fluently.Configure()
                                     .Database(MsSqlConfiguration.MsSql2012.ConnectionString(_ConnectionString))
                                     .Mappings(
                m =>
            {
                m.FluentMappings
                .AddFromAssembly(currentAssembly)
                .Conventions
                .Add <StringSqlTypeConvention>();
                m.HbmMappings.AddFromAssembly(currentAssembly);
            }
                );

            return(fc.BuildConfiguration()
                   .SetProperty(NHibernateEnvironment.ReleaseConnections, "on_close")
                   .BuildSessionFactory());
        }