Beispiel #1
1
        /// <summary>
        /// 保存考试人信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int SaveExamUser(ExamUser model)
        {
            int id = -1;
            if (model != null)
            {
                var conf = new Configuration().Configure();
                ISession session = NHibernateHelper.GetSession();
                //配置NHibernate
                //在Configuration中添加HbmMapping
                conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<ExamUser>(), "ExamUserXML");
                //配置数据库架构元数据
                SchemaMetadataUpdater.QuoteTableAndColumns(conf);

                //建立SessionFactory
                var factory = conf.BuildSessionFactory();
                //打开Session做持久化数据
                using (session = factory.OpenSession())
                {
                    using (var tx = session.BeginTransaction())
                    {
                        id = (int)session.Save(model);
                        tx.Commit();
                    }
                }
            }
            return id;
        }
		public void CanSetDefaultFlushModeThroughLoquaciousConfiguration()
		{
			var cfg = new Configuration()
				.Configure();

			cfg
				.SessionFactory()
				.DefaultFlushMode(FlushMode.Always);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				using (var session = sessionFactory.OpenSession())
				{
					Assert.AreEqual(FlushMode.Always, session.FlushMode);
				}
			}

			cfg.Configure()
				.SessionFactory()
				.DefaultFlushMode(FlushMode.Commit);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				using (var session = sessionFactory.OpenSession())
				{
					Assert.AreEqual(FlushMode.Commit, session.FlushMode);
				}
			}
		}
 public static Boolean TestAccount(DatabaseAccountToken token, Boolean testMapping = false)
 {
     try
     {
         Configuration configuration = new Configuration();
         configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionString, token.ConnectionString);
         configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, String.Format("NHibernate.Driver.{0}", token.DatabaseDriver));
         configuration.SetProperty(NHibernate.Cfg.Environment.Dialect, String.Format("NHibernate.Dialect.{0}", token.DatabaseDialect));
         if (testMapping)
         {
             configuration.AddXml(token.Mapping);
             using (ISessionFactory sessionFactory = configuration.BuildSessionFactory())
             {
                 using (ISession session = sessionFactory.OpenSession())
                 {
                     return session.IsConnected;
                 }
             }
         }
         else
         {
             using (ISessionFactory sessionFactory = configuration.BuildSessionFactory())
             {
                 using (ISession session = sessionFactory.OpenSession())
                 {
                     return session.IsConnected;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         return false;
     }
 }
        ISessionFactory CreateSessionFactory()
        {
            try
            {
                bool acquired = _factoryMutex.WaitOne();
                if (!acquired)
                {
                    throw new InvalidOperationException("Waiting for access to create session factory failed.");
                }

                ISessionFactory sessionFactory = _configuration.BuildSessionFactory();

                _sessionFactory = sessionFactory;
                _computed       = true;

                return(sessionFactory);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("Failed to create session factory"), ex);
            }
            finally
            {
                _factoryMutex.ReleaseMutex();
            }
        }
        static void Main(string[] args)
        {
            #region NHibernate
            var hibernateConfig = new Configuration();
            hibernateConfig.DataBaseIntegration(x =>
            {
                x.ConnectionStringName = "NServiceBus/Persistence";
                x.Dialect <MsSql2012Dialect>();
            });
            var mapper = new ModelMapper();
            mapper.AddMapping <OrderMap>();
            hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SessionFactory = hibernateConfig.BuildSessionFactory();
            #endregion

            new SchemaExport(hibernateConfig).Execute(false, true, false);

            #region ReceiverConfiguration
            var busConfig = new BusConfiguration();
            busConfig.UseTransport <SqlServerTransport>().UseSpecificConnectionInformation(
                EndpointConnectionInfo.For("sender")
                .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True"));

            busConfig.UsePersistence <NHibernatePersistence>();
            busConfig.EnableOutbox();
            #endregion

            using (Bus.Create(busConfig).Start())
            {
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
            }
        }
        private void InitSessionFactory()
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            var mapeamentoDominio = mapper.CompileMappingForAllExplicitlyAddedEntities();


            //var testStrinConecao = "Data Source=189.36.10.90,49433;Initial Catalog=ProIntegracao;Persist Security Info=True;User ID=mfranco;Password=M@rcelo1988"; //System.Configuration.ConfigurationSettings.AppSettings["ConexaoSQL.0"];


            var configuration = new NHibernate.Cfg.Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect <MsSql2008Dialect>();
                c.ConnectionString   = ObterStringConexao();//System.Configuration.ConfigurationSettings.AppSettings["ConexaoSQL.0"];
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            }).AddMapping(mapeamentoDominio);

            configuration.AddAssembly("ProIntegracao.Data");

            _sessionFactory = configuration.BuildSessionFactory();
        }
        static public ISessionFactory GetSF()
        {
            try
            {
                if (_SF == null)
                {
                    var nhCnfig = new NHibernate.Cfg.Configuration();

                    nhCnfig.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties abc)
                    {
                        abc.ConnectionString = "Database=test_db;Data Source=localhost;Port=3306;User Id=root;Password=1234";
                        abc.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                        abc.Driver <NHibernate.Driver.MySqlDataDriver>();
                        abc.Timeout = 60;
                    }
                                                );
                    //one of your model in our case we just have one model
                    nhCnfig.AddAssembly(typeof(TestTable).Assembly);
                    nhCnfig.CurrentSessionContext <WebSessionContext>();
                    _SF = nhCnfig.BuildSessionFactory();
                }
            }

            catch (Exception ex)
            { }


            return(_SF);
        }
Beispiel #8
0
        /// <summary>
        /// Método que crea la session factory
        /// </summary>
        public ISessionFactory SessionFactory()
        {
            try
            {
                //Siempre que no la hayamos creado antes
                if (_sessionFactory == null)
                {
                    var cfg = new NHibernate.Cfg.Configuration();
                    cfg.Configure();

                    var mapper = new ModelMapper();

                    //Especifico uno por unos los mapeos de las entidades
                    //mapper.AddMappings(typeof(BE.AfiliadoDatos).Assembly.GetTypes());
                    mapper.AddMapping <MapAfiBeneficiariosOspep>();
                    mapper.AddMapping <MapTest>();
                    mapper.AddMapping <MapAuditoriaWS>();
                    mapper.AddMapping <MapAfiBeneficiarios>();

                    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                    cfg.AddMapping(mapping);

                    _sessionFactory = cfg.BuildSessionFactory();
                }
                return(_sessionFactory);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        public ISessionFactory GetSessionFactory(NHibernate.Cfg.Configuration cfg)
        {
            // Note: Troubleshooting
            // At some point here, I was getting error which got resolved due to this:
            // https://stackoverflow.com/questions/35444487/how-to-use-sqlclient-in-asp-net-core
            //            Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:
            //            System.Data.Common and System.Data.SqlClient


            var sefact = cfg.BuildSessionFactory();

            // Later on, use like this:

            //using (var session = sefact.OpenSession())
            //{
            //    using (var tx = session.BeginTransaction())
            //    {
            //        //perform database logic 
            //        tx.Commit();
            //    }
            //    Console.ReadLine();
            //}

            return sefact;
        }
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] 
            { 
                new TestSaveOrUpdateEventListener()
            };

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message() { Content = "Message1" });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
		public void SetUp() {
			if (this._sessionFactory == null) {
				var cfg = new Configuration();
				cfg.Configure();
				this._sessionFactory = cfg.BuildSessionFactory();
			}
		}
		private static void Init()
		{
			var config = new Configuration();
			config.Configure();
			config.AddAssembly(Assembly.GetCallingAssembly());
			_sessionFactory = config.BuildSessionFactory();
		}
Beispiel #13
0
        static NHibernateHelper()
        {
            NHibernate.Cfg.Configuration cfg = null;

#if HIBERNATE_CFG_CODE
            cfg = new NHibernate.Cfg.Configuration()
                  .DataBaseIntegration(db =>
            {
                db.ConnectionString = ConfigurationManager.
                                      ConnectionStrings[Constants.DB_CONNECTION_STRING_NAME].
                                      ConnectionString;
                db.Dialect <MsSql2008Dialect>();
                db.Driver <NHibernate.Driver.SqlClientDriver>();
                db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
            });
#else
            cfg = new NHibernate.Cfg.Configuration().Configure();
#endif

#if HIBERNATE_MAP_CODE
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(mapping);
#else
            // Автоматический маппинг всей сборки, содержащей типы сущностей
            configuration.AddAssembly(typeof(< type_name >).Assembly);
#endif

            new SchemaUpdate(cfg).Execute(true, true);
            sessionFactory = cfg.BuildSessionFactory();
        }
Beispiel #14
0
 private static void Init()
 {
     nhConfiguration = new Configuration();
     //nhConfiguration.Configure("NhibernateUtils/NHibernate.cfg.xml");
     nhConfiguration.AddAssembly("Activos");
     sessionFactory = nhConfiguration.BuildSessionFactory();
 }
Beispiel #15
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            var log4NetPath = Server.MapPath("~/log4net.config");

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(log4NetPath));

            try
            {
                var hConfiguration = new NHibernate.Cfg.Configuration();

                hConfiguration.AddAssembly("BudgetORM");
                hConfiguration.AddAssembly("iSabayaORM");
                hConfiguration.AddAssembly("iSabaya.ExtensibleORM");

                SessionFactory = hConfiguration.BuildSessionFactory();
            }
            catch //(Exception exc)
            {
            }
        }
Beispiel #16
0
        public static void Initialize()
        {
            NhibernateConfiguration = new Configuration().Configure();

            // Mapping by Mapping XML-Files
            foreach (var xmlMappingAssembly in GetXmlMappingAssemblies())
            {
                NhibernateConfiguration.AddAssembly(xmlMappingAssembly);
            }

            // Mapping by Code
            var modelMapper = new ModelMapper();

            foreach (var modelAssembly in GetModelAssemblies())
            {
                modelMapper.AddMappings(modelAssembly.GetExportedTypes());
                NhibernateConfiguration.AddAssembly(modelAssembly);
            }
            if (GetModelAssemblies().Any())
            {
                HbmMapping domainMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                NhibernateConfiguration.AddMapping(domainMapping);
            }

            SessionFactory = NhibernateConfiguration.BuildSessionFactory();
        }
 public static void TestClassSetup(TestContext context)
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Draft).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
        private static void InitNHibernate()
        {
            lock (LockObject)
            {
                if (_sessionFactory == null)
                {
                    // Создание NHibernate-конфигурации приложения на основании описаний из web.config.
                    // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, 
                    // заданные в xml-файлах.
                    var configure = new Configuration().Configure();

                    // Настройка маппинга, созданного при помощи mapping-by-code
                    var mapper = new ModelMapper();
                    mapper.AddMappings(new List<Type>
                    {
                        // Перечень классов, описывающих маппинг
                        typeof (DocumentTypeMap),
                        typeof (DocumentMap),
                        typeof (DocumentWithVersionMap),
                    });
                    // Добавление маппинга, созданного при помощи mapping-by-code, 
                    // в NHibernate-конфигурацию приложения
                    configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
                    //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>();
                    //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>();
                    configure.DataBaseIntegration(x =>
                    {
                        x.LogSqlInConsole = true;
                        x.LogFormattedSql = true;
                    });

                    _sessionFactory = configure.BuildSessionFactory();
                }
            }
        }
Beispiel #19
0
        public static void Initialize()
        {
            NhibernateConfiguration = new Configuration();
            NhibernateConfiguration.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName;
            NhibernateConfiguration.Configure();

            // Mapping by Mapping XML-Files
            foreach (var xmlMappingAssembly in GetXmlMappingAssemblies())
            {
                NhibernateConfiguration.AddAssembly(xmlMappingAssembly);
            }

            // Mapping by Code
            var modelMapper = new ModelMapper();

            foreach (var modelAssembly in GetModelAssemblies())
            {
                modelMapper.AddMappings(modelAssembly.GetExportedTypes());
                NhibernateConfiguration.AddAssembly(modelAssembly);
            }
            if (GetModelAssemblies().Any())
            {
                HbmMapping domainMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                NhibernateConfiguration.AddMapping(domainMapping);
            }


            SessionFactory = NhibernateConfiguration.BuildSessionFactory();
        }
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.SetListener(ListenerType.PreUpdate, new TestUpdateEventListener());

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message() { Content = "Message1", Creator = "Leoli_EventTest" });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
Beispiel #21
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();

        Configuration configuration = new Configuration();
        configuration.Configure();
        configuration.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none");
        configuration.AddAssembly(typeof(Categoria).Assembly);

        new SchemaExport(configuration).Execute(true, false, false);

        ISessionFactory sessionFactory = configuration.BuildSessionFactory();

        //updateCategoria(sessionFactory);

        //insertCategoria(sessionFactory);

        //loadArticulo(sessionFactory);

        ISession session = sessionFactory.OpenSession();
        ICriteria criteria = session.CreateCriteria(typeof(Articulo));
        criteria.SetFetchMode("Categoria", FetchMode.Join);
        IList  list = criteria.List();
        foreach (Articulo articulo in list)
            Console.WriteLine("Articulo Id={0} Nombre={1} Precio={2} Categoria={3}",
                              articulo.Id, articulo.Nombre, articulo.Precio, articulo.Categoria);

        session.Close();

        sessionFactory.Close();
    }
Beispiel #22
0
        public static ISession OpenSession()
        {
            if (sessionFactory == null)
            {
                System.Collections.Specialized.NameValueCollection sets = System.Configuration.ConfigurationManager.AppSettings;

                //获取连接字符串
                string server = Utilities.GetConfigValue("server");
                string pwd = VTMS.Common.Utilities.Base64Dencrypt(Utilities.GetConfigValue("DBPassword"));
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
                connectionString = string.Format(connectionString, server, pwd);

                try
                {
                    Configuration cfg = new Configuration().Configure();
                    cfg.Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>());
                    cfg.DataBaseIntegration(db =>
                    {
                        db.ConnectionString = connectionString;
                    });

                    sessionFactory = cfg.BuildSessionFactory();
                }
                catch (Exception e)
                {
                    VTMS.Common.MessageUtil.ShowError("无法登陆服务器,请检查服务器IP设置是否正确,错误信息为:" + e.Message);
                }
            }
            return sessionFactory.OpenSession();
        }
Beispiel #23
0
        internal DatabaseSessionFactory(NHibernate.Cfg.Configuration nhibernateConfig, bool reBuildSessionFactory = false)
        {
            string sessionFactoryKey = nhibernateConfig.GetProperty("session_factory_name");

            if (sessionFactoryDict.ContainsKey(sessionFactoryKey) && !reBuildSessionFactory)
            {
                sessionFactory = sessionFactoryDict[sessionFactoryKey];
            }
            else
            {
                //TODO:调试用的
                //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

                sessionFactory = nhibernateConfig.BuildSessionFactory();

                if (BuildedSessionFactory != null)
                {
                    BuildedSessionFactory(sessionFactory);
                }

                lock (helpLock)
                {
                    if (sessionFactoryDict.ContainsKey(sessionFactoryKey))
                    {
                        sessionFactoryDict[sessionFactoryKey] = sessionFactory;
                    }
                    else
                    {
                        sessionFactoryDict.Add(sessionFactoryKey, sessionFactory);
                    }
                }
            }
            this.FactoryName = sessionFactoryKey;
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            var configuration = new Configuration().Configure("hibernate.cfg.xml");
            //configuration.AddAssembly("HibernateTest");
            var sessionFactory = configuration.BuildSessionFactory();
            var session = sessionFactory.OpenSession();

            var list = session.CreateCriteria<Product>().List<Product>();

            foreach (var l in list)
            {
                Console.WriteLine("{0:3} | {1:40} | {2:4}", l.ID, l.Name, l.Quantity);
            }

            using(ITransaction trans = session.BeginTransaction())
            {
                Product product = new Product();

                product.Name = "dupa";
                product.Quantity = 66;

                session.Save(product);
                trans.Commit();
            }

            Console.Read();
            session.Close();
        }
        public long saveOrder1()
        {
            ISessionFactory _sessions;
            Configuration cfg = new Configuration().Configure();
            _sessions = cfg.BuildSessionFactory();

            TOrderData ob = new TOrderData();
            ob.Configure();

            TOrder od = ob.CreateOrder("test", "order.Address", "order.Phone", "order.AddText",1);
            //od.Id = order.Id;
            //od.Name = order.Name;
            //od.OrderTime = order.OrderTime;
            //od.Phone = order.Phone;
            //od.Address = order.Address;
            //od.AddText = order.AddText;

                for (int i = 0; i < 8; i++)
                {
                    TOrderItem oditem = new TOrderItem();
                    oditem.Order = od;
                    oditem.Price = 9.99M;
                    oditem.Amount = 2;
                    oditem.SubPrice = 19.99M;
                    oditem.Text = "testb" + od.Id;
                    oditem.DishId = 1;
                    oditem.DishName = "testb" + i;
                    od.Items.Add(oditem);

                }
                ob.UpdateOrder(od);

                return od.Id;
        }
        public BusinessSafeSessionFactory()
        {
            var hibernateConfigFilePath = new NHibernateConfigPathGenerator(Database.BusinessSafe).GetConfigFilePath();
            Log4NetHelper.Logger.Debug("BusinessSafeSessionFactory() - NHibernate Configuration File path: " + hibernateConfigFilePath);

            var configuration = new Configuration();
            configuration.Configure(hibernateConfigFilePath);
            configuration.SetProperty(Environment.ConnectionStringName, "BusinessSafe");

            configuration.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };

            _sessionFactory = configuration.BuildSessionFactory();
        }
Beispiel #27
0
        static NHibernateManager()
        {
            Configuration cfg= new Configuration().Configure();
                //cfg.AddAssembly("App_SubCode_APAS");
                //cfg.AddClass(typeof(Apas.Business.BCOtherFeeType));

                //Business Persistent Entity Mappings
                cfg.AddDirectory(new System.IO.DirectoryInfo
                      (
                            HttpContext.Current.Server.MapPath
                            (
                                @"~/App_Code/APAS/Business/NHibernate Mappings/"
                             )
                         )
                    );

                //Security Layer Entity Mappings
                cfg.AddDirectory(new System.IO.DirectoryInfo
                    (
                        HttpContext.Current.Server.MapPath
                        (
                            @"~/App_Code/APAS/Security/NHibernate Mappings/"
                         )
                     )
                );

                sessionFactory= cfg.BuildSessionFactory();
        }
Beispiel #28
0
        /// <summary>
        /// Initializes the mappings.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void InitMappings(Configuration config)
        {
            var orm = new ObjectRelationalMapper();

            var mapper = new Mapper(orm);

            mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && !mi.Name.EndsWith("Text"), pm => pm.Length(50));
            mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.EndsWith("Text"), pm => pm.Type(NHibernateUtil.StringClob));

            orm.Patterns.PoidStrategies.Add(new AssignedPoidPattern());

            foreach (var componentDbInit in IoC.ResolveAllInstances<IComponentDbInit>())
            {
                componentDbInit.InitMappings(orm, mapper);
            }

            // compile the mapping for the specified entities
            HbmMapping mappingDocument = mapper.CompileMappingFor(ListOfModelTypes());

            // inject the mapping in NHibernate
            config.AddDeserializedMapping(mappingDocument, "Domain");
            // fix up the schema
            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            SessionFactory.SessionFactoryInstance = config.BuildSessionFactory();
        }
Beispiel #29
0
        public void TestMethod1()
        {
            var config = new NH.Configuration().Configure();

            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(SessionFactory).Assembly.GetTypes());
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SchemaUpdate su = new SchemaUpdate(config);

            //se.Execute(false, false, true);
            su.Execute(true, true);

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    session.Save(new Brand {
                        Name = "Brand 2", UtcCreationDate = DateTime.UtcNow, UtcUpdateDate = DateTime.UtcNow
                    });
                    tran.Commit();
                }
            }

            factory.Dispose();
        }
Beispiel #30
0
        private ISessionFactory CreateSessionFactory()
        {
            var container = new FluentMappingsContainer();

            var mainConnectionString = ConfigurationManager.ConnectionStrings["MainDataStore"]?.ConnectionString;

            //mainConnectionString = Encryption.Encrypt(mainConnectionString, AppSettings.ApplicationPassPhrase);

            //mainConnectionString = Encryption.Decrypt(mainConnectionString, AppSettings.ApplicationPassPhrase);

            if (String.IsNullOrWhiteSpace(mainConnectionString))
            {
                throw new ArgumentNullException("MainDataStore connection string property in web.config does not contain a value for connection string");
            }

            Configuration = CreateNewConfigurationUsingConnectionString(mainConnectionString);

            try
            {
                var result = Configuration.BuildSessionFactory();
                return(result);
            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
                throw;
            }
        }
        /// <summary>
        /// Se crea la configuración de inicio de la aplicación y
        /// muestra, usando la vista Index.cshtml la pagina de iniio
        /// </summary>
        /// <returns>Devuelve Index.cshtml, la vista asociada a la funcion Index()</returns>
        public ActionResult Index()
        {
            myConfiguration = new NHibernate.Cfg.Configuration();
            myConfiguration.Configure();
            myISessionFactory = myConfiguration.BuildSessionFactory();
            myISession        = myISessionFactory.OpenSession();
            string msgSalida = "";

            using (SqlConnection con = new SqlConnection(conString))
            {
                try//tratamos de crear la tabla, si existe atrapa la excepcion y lanza el mensaje correspondiente
                {
                    // Abrir conexion sql.
                    con.Open();
                    // Creamos la tabla.
                    using (SqlCommand command = new SqlCommand("CREATE TABLE requests (id int IDENTITY(1,1) PRIMARY KEY, request text NOT NULL);", con))
                    {
                        command.ExecuteNonQuery();//verificamos que el comando afecta la base de datos
                        msgSalida = "La tabla requests no existe, creando tabla en base de datos";
                    }
                }
                catch (Exception ex)
                {
                    msgSalida = "La tabla requests ya existe, no es necesario crearla.";
                }
            }
            ViewData["msgSalida"] = msgSalida;
            return(View());
        }
        /// <summary>
        /// Configures the storage with the user supplied persistence configuration
        /// Azure tables are created if requested by the user
        /// </summary>
        /// <param name="config"></param>
        /// <param name="connectionString"></param>
        /// <param name="createSchema"></param>
        /// <returns></returns>
        public static Configure AzureSubcriptionStorage(this Configure config,
            string connectionString,
            bool createSchema,
            string tableName)
        {
            var cfg = new Configuration()
            .DataBaseIntegration(x =>
                                   {
                                     x.ConnectionString = connectionString;
                                     x.ConnectionProvider<TableStorageConnectionProvider>();
                                     x.Dialect<TableStorageDialect>();
                                     x.Driver<TableStorageDriver>();
                                   });

               SubscriptionMap.TableName = tableName;

              var mapper = new ModelMapper();
              mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
              var faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

              cfg.AddMapping(faultMappings);

              if (createSchema)
              {
            new SchemaExport(cfg).Execute(true, true, false);
              }

              var sessionSource = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory());

            config.Configurer.RegisterSingleton<ISubscriptionStorageSessionProvider>(sessionSource);

            config.Configurer.ConfigureComponent<SubscriptionStorage>(DependencyLifecycle.InstancePerCall);

            return config;
        }
Beispiel #33
0
        private ISessionFactory BuildSessionFactory()
        {
            Logger.Debug("Building session factory");

            NHibernate.Cfg.Configuration config = GetConfiguration();
            return(config.BuildSessionFactory());
        }
Beispiel #34
0
        public void Install(IServiceCollection services)
        {
            var connectionString = ConfigurationManager.AppSettings[SettingKeys.MainConnectionString] ?? throw new ArgumentException("Connection string not found");

            var cfg = new Configuration()
                      .DataBaseIntegration(db =>
            {
                db.ConnectionString = connectionString;
                db.Dialect <MsSql2008Dialect>();
                db.Driver <SqlClientDriver>();
                db.ConnectionProvider <DriverConnectionProvider>();
                db.BatchSize = 5000;
                db.Timeout   = byte.MaxValue;
                //db.LogFormattedSql = true;
                //db.LogSqlInConsole = true;
            })
                      .AddAssembly(typeof(DataEntitiesContainerRegistration).Assembly);

            var sessionFactory = cfg.BuildSessionFactory();

            services.AddSingleton(cfg);

            services.AddSingleton(sessionFactory);

            services.AddScoped <IUnitOfWork, UnitOfWork>();
        }
		public void MixingParametersAndValues()
		{
			Configuration cfg = new Configuration();
			ISessionFactory factory = cfg.BuildSessionFactory();

			ISessionFactoryImplementor factoryImpl = (ISessionFactoryImplementor)factory;
			SqlInsertBuilder insert = new SqlInsertBuilder(factoryImpl);

			insert.SetTableName("test_insert_builder");

			insert.AddColumn("literalColumn", false, (ILiteralType)NHibernateUtil.Boolean);
			insert.AddColumn("intColumn", NHibernateUtil.Int32);
			insert.AddColumn("stringColumn", 5.ToString());
			insert.AddColumn("longColumn", NHibernateUtil.Int64);

			SqlCommandInfo sqlCommand = insert.ToSqlCommandInfo();
			SqlType[] actualParameterTypes = sqlCommand.ParameterTypes;

            string falseString = factoryImpl.Dialect.ToBooleanValueString(false);
            string expectedSql =
                "INSERT INTO test_insert_builder (literalColumn, intColumn, stringColumn, longColumn) VALUES (" + falseString + ", ?, 5, ?)";
			Assert.AreEqual(expectedSql, sqlCommand.Text.ToString(), "SQL String");

			Assert.AreEqual(2, actualParameterTypes.Length);
			Assert.AreEqual(SqlTypeFactory.Int32, actualParameterTypes[0], "First Parameter Type");
			Assert.AreEqual(SqlTypeFactory.Int64, actualParameterTypes[1], "Second Parameter Type");			
		}
Beispiel #36
0
		/// <summary>
		/// Called by the framework to initialize the persistent store.
		/// </summary>
		public void Initialize()
		{
			Platform.Log(LogLevel.Info, "Initializing NHibernate subsystem...");

			// create the hibernate configuration
			_cfg = new Configuration();

			// this will automatically read from the app.config
			_cfg.Configure();

			Platform.Log(LogLevel.Debug, "NHibernate connection string: {0}", this.ConnectionString);

			// add each assembly to the hibernate configuration
			// this tells NHibernate to look for .hbm.xml embedded resources in these assemblies
			// TODO: we should only scan plugins that are tied to this PersistentStore, but there is currently no way to know this
			var orderer = new AssembliesHbmOrderer(Platform.PluginManager.Plugins);
			orderer.AddToConfiguration(_cfg);

			// setup default caching strategies for all classes/collections that don't have one explicitly
			// specified in the mapping files
			CreateDefaultCacheStrategies();

			// create the session factory
			_sessionFactory = _cfg.BuildSessionFactory();

			Platform.Log(LogLevel.Info, "NHibernate initialization complete.");
		}
        private void button1_Click(object sender, EventArgs e)
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Domain.User).Assembly);

            var sessions = cfg.BuildSessionFactory();
            var sess = sessions.OpenSession();
            var new_user = new Domain.User

            {
                Name = textBox1.Text,
                Surname = textBox2.Text,
                Patronymic = textBox3.Text,
                Role_id = 1,
                Login = textBox4.Text,
                Pass = textBox5.Text
            };
            if (new_user.Name.Length > 0 && new_user.Surname.Length > 0 && new_user.Patronymic.Length > 0 && new_user.Login.Length > 0 && new_user.Pass.Length > 0)
            {
                sess.Save(new_user);
                sess.Flush();
                this.Hide();
            }
            else
            {
                label6.Text = "Не все поля заполнены!";
            }
        }
 public void TestFixtureSetUp()
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Product).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
Beispiel #39
0
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[]
            {
                new TestSaveOrUpdateEventListener()
            };

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message()
                {
                    Content = "Message1"
                });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
        static public ISessionFactory GetSF()
        {
            try
            {
                if (_SF == null)
                {
                    var nhCnfig = new NHibernate.Cfg.Configuration();

                    nhCnfig.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties abc)
                    {
                        abc.ConnectionString = "Database=rides;Data Source=localhost;Port=3306;User Id=root;Password=<K%F!1?qsYt0";
                        abc.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                        abc.Driver <NHibernate.Driver.MySqlDataDriver>();
                        abc.LogSqlInConsole = true;
                        abc.Timeout         = 60;
                    });

                    nhCnfig.AddAssembly(typeof(Templar).Assembly);
                    nhCnfig.CurrentSessionContext <WebSessionContext>();

                    _SF = nhCnfig.BuildSessionFactory();
                }
            }

            catch (Exception ex)
            { }

            return(_SF);
        }
Beispiel #41
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.SetListener(ListenerType.PreUpdate, new TestUpdateEventListener());

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message()
                {
                    Content = "Message1", Creator = "Leoli_EventTest"
                });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
        /// <summary>
        /// Creates session factory
        /// </summary>
        /// <param name="configurationReader">configuration reader</param>
        /// <returns></returns>
        private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader)
        {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.SessionFactoryName("Jumblocks Blog");

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2008FixedDialect>();
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString;
                db.BatchSize = 100;

                //for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                db.AutoCommentSql = true;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<BlogPostMap>();
            mapper.AddMapping<BlogUserMap>();
            mapper.AddMapping<ImageReferenceMap>();
            mapper.AddMapping<TagMap>();
            mapper.AddMapping<SeriesMap>();

            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<OperationMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            configuration.CurrentSessionContext<WebSessionContext>();

            return configuration.BuildSessionFactory();
        }
        public static void AddNHibernateSessionFactory(this IServiceCollection services)
        {
            // By default NHibernate looks for hibernate.cfg.xml
            // otherwise for Web it will fallback to web.config
            // we got one under wwwroot/web.config
            Configuration config = new Configuration();
            config.Configure();

            // Auto load entity mapping class
            ModelMapper mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddDeserializedMapping(mapping, "NHibernate.Mapping");

            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            // Drop & Recreate database schema
            new SchemaExport(config).Drop(false, true);
            new SchemaExport(config).Create(false, true);

            // Register services
            services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
            services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assemblyNames">The names of the assemblies containing object-relational mapping information</param>
        /// <exception cref="Exception">Thrown if an error occurred while constructing the factory</exception>
        public ReaderFactory(IEnumerable<string> assemblyNames)
        {
            Exception exception = null;

            // If SessionFactory build fails then retry
            for (int tryNumber = 1; tryNumber <= 3; tryNumber++)
            {
                try
                {
                    Configuration config = new Configuration();

                    // Add assemblies containing mapping definitions
                    foreach (string assemblyName in assemblyNames)
                    {
                        config.AddAssembly(assemblyName);
                    }

                    config.Configure();
                    sessionFactory = config.BuildSessionFactory();

                    // SessionFactory built successfully
                    exception = null;
                    break;
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            }

            if (exception != null)
            {
                throw new FingertipsException("Could not construct ReaderFactory instance", exception);
            }
        }
        /// <summary>
        /// Carga las listas de la BD que se necesitan para las consultas
        /// </summary>
        private void CargarListas()
        {
            //Iniciar sesión
            var cfg = new Configuration();
            cfg.Configure();
            var sessions = cfg.BuildSessionFactory();
            var sess = sessions.OpenSession();

            //Consulta a la BD
            IQuery q1 = sess.CreateQuery("FROM Cliente");
            var clientesTodos = q1.List<Cliente>();

            //Actualización de la lista global de clientes
            clientes = clientesTodos.ToList<Cliente>();

            //Consulta a la BD
            IQuery q2 = sess.CreateQuery("FROM Empleada");
            var empleadosTodos = q2.List<Empleada>();

            //Actualización de la lista global de clientes
            empleados = empleadosTodos.ToList<Empleada>();

            //Carga en las tablas
            sess.Close();
        }
Beispiel #46
0
        private static void CreateStuff(Configuration cfg)
        {
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory())
            using (ISession session = sessionFactory.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                try
                {
                    var tempUser = new User { Username = "******" };
                    session.Save(tempUser);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.ResetColor();
                    transaction.Rollback();
                }
                finally
                {
                    session.Close();
                }
            }
        }
Beispiel #47
0
        public UserInfo GetUserInfoById(int userId)
        {
            Configuration cfg = new Configuration().Configure(path);

            ISession session = cfg.BuildSessionFactory().OpenSession();
            return session.Get<UserInfo>(userId);
        }
Beispiel #48
0
        /// <summary>
        /// 根据试卷ID和试题ID删除试卷试题
        /// </summary>
        /// <param name="PaperId"></param>
        /// <param name="QuestionsId"></param>
        /// <returns></returns>
        public static int DeletePaperQuestions(int PaperId, int QuestionsId)
        {
            int number = -1;
            ISession session = NHibernateHelper.GetSession();
            //配置NHibernate
            var conf = new Configuration().Configure();
            //在Configuration中添加HbmMapping
            conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<PaperQuestions>(), "PaperQuestionsXML");
            //配置数据库架构元数据
            SchemaMetadataUpdater.QuoteTableAndColumns(conf);

            //建立SessionFactory
            var factory = conf.BuildSessionFactory();
            //打开Session做持久化数据
            using (session = factory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    //var query = session.QueryOver<PaperQuestions>()
                    //.Where(p => p.PaperId == PaperId)
                    //.Where(p => p.QuestionsId == QuestionsId)
                    ////.Where("Name like '%我的测试'")
                    ////.OrderBy(p => p.TypeID).Asc
                    //.List();
                    number = session.Delete ("from PaperQuestions p Where p.PaperId=" + PaperId.ToString() + " and p.QuestionsId = " + QuestionsId.ToString());
                    //number = session.CreateQuery("delete from PaperQuestions Where PaperId=" + PaperId.ToString() + " and QuestionsId = " + QuestionsId.ToString()).ExecuteUpdate();
                    //var domain = new Domain { Id = 1, Name = "我的测试" + DateTime.Now.ToString() };
                    //s.Delete(domain);
                    tx.Commit();
                    return number;
                }
            }
        }
        private static void CreateSessionFactory()
        {
            // FluentNHibernate.Search Configuration
            Configuration fnhscfg = FluentSearch.Configure()
                .DefaultAnalyzer().Standard()
                .DirectoryProvider().RAMDirectory()
                .IndexingStrategy().Event()
                .Listeners(ListenerConfiguration.Default)
                .MappingClass<SearchMap>()
                .BuildConfiguration();

            // FluentNHibernate Configuration
            Configuration fnhcfg = Fluently.Configure(fnhscfg)
                    .Database(SQLiteConfiguration.Standard.InMemory()
                    .Dialect<SQLiteDialect>()
                    .ConnectionString(ConnectionString)
                    .ProxyFactoryFactory<ProxyFactoryFactory>())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<AuthorMap>())
                .ExposeConfiguration(cfg =>
                                         {
                                             cfg.SetListeners(ListenerType.PostInsert, new[] { new FullTextIndexEventListener() });
                                             cfg.SetListeners(ListenerType.PostUpdate, new[] { new FullTextIndexEventListener() });
                                             cfg.SetListeners(ListenerType.PostDelete, new[] { new FullTextIndexEventListener() });

                                             cfg.SetListener(ListenerType.PostCollectionRecreate, new FullTextIndexCollectionEventListener());
                                             cfg.SetListener(ListenerType.PostCollectionRemove, new FullTextIndexCollectionEventListener());
                                             cfg.SetListener(ListenerType.PostCollectionUpdate, new FullTextIndexCollectionEventListener());
                                         })
                .BuildConfiguration();

            _cfg = fnhcfg;
            _sessionFactory = _cfg.BuildSessionFactory();
        }
Beispiel #50
0
        public ISessionFactory CreateSessionFactory()
        {
            NHibernate.Cfg.Configuration configuration = GetConfiguration();

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }
Beispiel #51
0
 static NHibernateHelper()
 {
     //connectionString = "Server=pos744;Initial Catalog=n7682905;Integrated Security=SSPI;";
     GetAppConnectionString();
     NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
     cfg.Properties["connection.connection_string"] = connectionString;
     sessionFactory = cfg.BuildSessionFactory();
 }
Beispiel #52
0
 public ISessionFactory CreateSessionFactory()
 {
     if (!Configured)
     {
         Configure();
     }
     return(Configuration.BuildSessionFactory());
 }
Beispiel #53
0
        static NHSession()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration().Configure();

            config.SetProperty("connection.connection_string", ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

            sessionfactory = config.BuildSessionFactory();
        }
Beispiel #54
0
        /// <summary>
        /// Configures the NHibernate session.
        /// </summary>
        /// <param name="configurationProvider">The configuration provider.</param>
        /// <param name="container">The container.</param>
        protected override void ConfigureNHibernateSession(IConfigurationProvider configurationProvider, IContainer container)
        {
            NHibernate.Cfg.Configuration configuration = configurationProvider.Configure().GetEnumerator().Current;
            ISessionFactory sessionFactory             = configuration.BuildSessionFactory();

            container.Configure(x => x.For <ISessionFactory> ().Singleton().Use(sessionFactory));
            container.Configure(
                x => x.For <ISession> ().LifecycleIs(new NServiceBusThreadLocalStorageLifestyle()).Use(sessionFactory.OpenSession));
        }
        /// <summary>
        /// Create a nhibernate Session Factory for Given client
        /// </summary>
        /// <returns></returns>

        public static ISessionFactory GetSessionFactory()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();

            ISessionFactory sessionFactory = cfg.BuildSessionFactory();

            return(sessionFactory);
        }
Beispiel #56
0
        static BaseTestFixture()
        {
            _config = new NHibernate.Cfg.Configuration();
            _config.AddAssembly("DomainObjects");

            if (_sessionFactory == null)
            {
                _sessionFactory = _config.BuildSessionFactory();
            }
        }
Beispiel #57
0
        static DataAccesser()
        {
            //NHibernate's Config Initialize
            config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.AddClass(typeof(Computer));

            //SessionFactory Initialize
            sessionFactory = config.BuildSessionFactory();
        }
Beispiel #58
0
        ISession OpenSession()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure("hibernate-attr.cfg.xml");

            NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional)
            cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetAssembly(typeof(DeliveryOrder))));
            ISessionFactory f = cfg.BuildSessionFactory();

            return(f.OpenSession());
        }
        public ISessionFactory SetUpSessionFactory()
        {
            Configuration = ReadConfigFromCacheFileOrBuildIt();

            var sessionFactory = Configuration.BuildSessionFactory();

            //if (DropTablesCreateDbSchema)
            //    ConfirmDatabaseMatchesMappings.TryValidateAndUpdateDatabaseSchema(Configuration, sessionFactory);

            return(sessionFactory);
        }
Beispiel #60
0
        public static ISessionFactory GetSessionFactory()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(SessionFactoryFactory).Assembly.GetName().Name);
            log4net.Config.XmlConfigurator.Configure();
            var sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }