Example #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;
        }
Example #2
0
        private static Configuration ConfigureNHibernate()
        {
            var configure = new Configuration();

            configure.SessionFactoryName("BuildIt");

            configure.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.Driver <Sql2008ClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel     = IsolationLevel.ReadCommitted;

                db.ConnectionStringName = "TestDB";
                db.Timeout = 10;

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

            var mapping = GetMappings();

            configure.AddDeserializedMapping(mapping, "NHSchemaTest");
            SchemaMetadataUpdater.QuoteTableAndColumns(configure);

            return(configure);
        }
        public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration) {
            Type baseEntityType = typeof(Entity);

            mapper.IsEntity((type, declared) => IsEntity(type));
            mapper.IsRootEntity((type, declared) => baseEntityType.Equals(type.BaseType));

            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) => {
                classCustomizer.Id(c => c.Column("Id"));
                classCustomizer.Id(c => c.Generator(Generators.Identity));
                classCustomizer.Table(Inflector.Net.Inflector.Pluralize(type.Name.ToString()));
            };

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) => {
                map.Column(propertyPath.LocalMember.GetPropertyOrFieldType().Name + "Fk");
                map.Cascade(Cascade.Persist);
            };

            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => {
                map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Fk"));
                map.Cascade(Cascade.All);
            };

            AddConventionOverrides(mapper);

            HbmMapping mapping = mapper.CompileMappingFor(typeof(ActionConfirmation<>).Assembly.GetExportedTypes().Where(t => IsEntity(t)));
            configuration.AddDeserializedMapping(mapping, "TemplateSrcMappings");
        }
Example #4
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;
                }
            }
        }
        public Configuration BuildConfiguration(string connectionString, string sessionFactoryName)
        {
            Contract.Requires(!string.IsNullOrEmpty(connectionString), "ConnectionString is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(sessionFactoryName), "SessionFactory name is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(_databaseSchema), "Database Schema is null or empty");
            Contract.Requires(_configurator != null, "Configurator is null");

            return CatchExceptionHelper.TryCatchFunction(
                () =>
                {
                    DomainTypes = GetTypeOfEntities(_assemblies);

                    if (DomainTypes == null)
                        throw new Exception("Type of domains is null");

                    var configure = new Configuration();
                    configure.SessionFactoryName(sessionFactoryName);

                    configure.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>());
                    configure.DataBaseIntegration(db => GetDatabaseIntegration(db, connectionString));

                    if (_configurator.GetAppSettingString("IsCreateNewDatabase").ConvertToBoolean())
                    {
                        configure.SetProperty("hbm2ddl.auto", "create-drop");
                    }

                    configure.Properties.Add("default_schema", _databaseSchema);
                    configure.AddDeserializedMapping(GetMapping(),
                                                     _configurator.GetAppSettingString("DocumentFileName"));

                    SchemaMetadataUpdater.QuoteTableAndColumns(configure);

                    return configure;
                }, Logger);
        }
Example #6
0
        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool DeleteMember(Member model)
        {
            bool isSuccess = false;
            if (model != null)
            {
                var conf = new Configuration().Configure();
                ISession session = NHibernateHelper.GetSession();
                //配置NHibernate
                //在Configuration中添加HbmMapping
                conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<Member>(), "MemberXML");
                //配置数据库架构元数据
                SchemaMetadataUpdater.QuoteTableAndColumns(conf);

                //建立SessionFactory
                var factory = conf.BuildSessionFactory();
                //打开Session做持久化数据
                using (session = factory.OpenSession())
                {
                    using (var tx = session.BeginTransaction())
                    {
                        session.Delete(model);
                        tx.Commit();
                        isSuccess = true;
                    }
                }
            }
            return isSuccess;
        }
Example #7
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static IList<Notic> GetNewsList(string SystemName, int Num)
        {
            ISession session = NHibernateHelper.GetSession();
            //配置NHibernate
            var conf = new Configuration().Configure();
            //在Configuration中添加HbmMapping
            conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<Notic>(), "NoticXML");
            //配置数据库架构元数据
            SchemaMetadataUpdater.QuoteTableAndColumns(conf);

            //建立SessionFactory
            var factory = conf.BuildSessionFactory();
            //打开Session做持久化数据
            using (session = factory.OpenSession())
            {
                IList<Notic> query;
                if (string.IsNullOrEmpty(SystemName))
                {
                    query = session.QueryOver<Notic>()
                    .OrderBy(p => p.CreateTime).Desc
                        .List();
                }
                else
                {
                    query = session.QueryOver<Notic>()
                    .Where(p => p.SystemName == SystemName)
                    .Where(p => p.Status != 2)
                    .OrderBy(p => p.CreateTime).Desc
                        .List();
                }

                return query;
            }
        }
Example #8
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");
            }
        }
		/// <summary>
		/// Configure NHibernate
		/// </summary>
		private static Configuration ConfigureNHibernate()
		{
			Configuration configure = new Configuration();
			configure.SessionFactoryName("SessionFactory");

			configure.DataBaseIntegration(db =>
				{
					db.Dialect<MsSql2008Dialect>();
					db.Driver<SqlClientDriver>();
					db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
					db.IsolationLevel = IsolationLevel.ReadCommitted;

					db.ConnectionStringName = RegtestingServerConfiguration.DefaultConnectionString;
					//db.Timeout = 10;

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

			HbmMapping hbmMapping = GetMappings();
			configure.AddDeserializedMapping(hbmMapping,"NHMapping");
			SchemaMetadataUpdater.QuoteTableAndColumns(configure);

			return configure;
		}
        static Configuration ConfigureNHibernate()
        {
            var configure = new Configuration();
            configure.SessionFactoryName("HemArkivAccess");

            configure.DataBaseIntegration(db =>
            {
                db.Dialect<NHibernate.JetDriver.JetDialect>();
                db.Driver<NHibernate.JetDriver.JetDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;

                db.ConnectionStringName = "HemArkivAccess";
                db.Timeout = 10;

                // enabled for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = false;
                db.AutoCommentSql = false;
                db.Timeout = 10;
                //db.ConnectionProvider<NHibernate.Connection.DriverConnectionProvider>();
            });

            var mapping = GetMappings();
            configure.AddDeserializedMapping(mapping, "HemArkivAccess");

            return configure;
        }
Example #11
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");
            }
        }
Example #12
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");
            }
        }
		public void SetUp()
		{
			var configuration = new Configuration();
			configuration
				.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true")
				.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, "create-drop")
				.SetProperty(NHibernate.Cfg.Environment.UseQueryCache, "true")
				.SetProperty(NHibernate.Cfg.Environment.CacheProvider, typeof (HashtableCacheProvider).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, "on_close")
				.SetProperty(NHibernate.Cfg.Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
				.SetProperty(NHibernate.Cfg.Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;");

			var assembly = Assembly.GetExecutingAssembly();

			var modelMapper = new ModelMapper();
			modelMapper.AddMappings(assembly.GetTypes());
			var hbms = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
			configuration.AddDeserializedMapping(hbms, assembly.GetName().Name);

			ConfigureSearch(configuration);

			sessionFactory = configuration.BuildSessionFactory();

			Session = sessionFactory.OpenSession();
			SearchSession = Search.CreateFullTextSession(Session);

			new SchemaExport(configuration)
				.Execute(false, true, false, Session.Connection, null);

			AfterSetup();
		}
Example #14
0
        static NHibernateHelper()
        {
            try
            {
                cfg = new Configuration();
                cfg.Configure("NHibernateQueryModelConfiguration.xml");

                var mapper = new ConventionModelMapper();
                //mapper.IsEntity((t, declared) => t.Namespace.StartsWith("Sample.QueryModel") || );

                mapper.AfterMapClass += (inspector, type, classCustomizer) =>
                {
                    classCustomizer.Lazy(false);
                    //classCustomizer.Id(m => m.Generator(new GuidGeneratorDef()));
                };
                var mapping = mapper.CompileMappingFor(
                    Assembly.Load("Sample.QueryModel").GetExportedTypes()
                    .Union(new Type[] {typeof(Version)}));
                var allmapping = mapping.AsString();

                cfg.AddDeserializedMapping(mapping, "AutoModel");
                _sessionFactory = cfg.BuildSessionFactory();
 
            }
            catch (Exception ex)
            {
                throw ex;
            }
         
        }
Example #15
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");
            }
        }
Example #16
0
        public void CriarSchema()
        {
            // Apenas no Init da Aplicação

            var config = new Configuration();

            config.DataBaseIntegration(c =>
            {
                c.Dialect<MsSql2012Dialect>();
                c.ConnectionStringName = "ExemploNH";
                c.LogFormattedSql = true;
                c.LogSqlInConsole = true;
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            var modelMapper = new ModelMapper();

            modelMapper.AddMappings(typeof (ProdutoMap).Assembly.GetExportedTypes());

            config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain");

            ISessionFactory sessionFactory = config.BuildSessionFactory();

            // NOTE: Estudar framework FluentMigration
            var schemaExport = new SchemaExport(config);

            schemaExport.Create(true, true);
        }
        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();
                }
            }
        }
Example #18
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();
        }
        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());
        }
 public void TestFixtureSetUp()
 {
     configuration = new Configuration();
     configuration.SessionFactory()
                  .Integrate.Using<SQLiteDialect>()
                  .Connected.Using("Data source=testdb")
                  .AutoQuoteKeywords()
                  .LogSqlInConsole()
                  .EnableLogFormattedSql();
     var mapper = new ConventionModelMapper();
     mapper.Class<Foo>(cm => { });
     mapper.Class<Bar>(cm => { });
     CustomizeMapping(mapper);
     var mappingDocument = mapper.CompileMappingForAllExplicitlyAddedEntities();
     new XmlSerializer(typeof(HbmMapping)).Serialize(Console.Out, mappingDocument);
     configuration.AddDeserializedMapping(mappingDocument, "Mappings");
     new SchemaExport(configuration).Create(true, true);
     sessionFactory = configuration.BuildSessionFactory();
     using (var session = sessionFactory.OpenSession())
     using (var tx = session.BeginTransaction())
     {
         var foo = new Foo { Bars = CreateCollection() };
         foo.Bars.Add(new Bar { Data = 1 });
         foo.Bars.Add(new Bar { Data = 2 });
         id = session.Save(foo);
         tx.Commit();
     }
     sessionFactory.Statistics.IsStatisticsEnabled = true;
 }
        public static Configuration ConfigureNHibernate()
        {
            var cfg = new Configuration();

            cfg.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2012Dialect>();
                db.Driver <SqlClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel     = IsolationLevel.ReadCommitted;

                db.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
                db.Timeout          = 10;

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

            var mapping = GetAllMappingsFromAssembly();

            cfg.AddDeserializedMapping(mapping, null);
            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

            return(cfg);
        }
Example #22
0
 public static void PrepareDatabase()
 {
     var configuration = new Configuration();
     configuration.Configure();
     HbmMapping mapping = GetMappings();
     configuration.AddDeserializedMapping(mapping, null);
     new SchemaUpdate(configuration).Execute(true, true);
 }
Example #23
0
        public DataBasesInit()
        {
            _nhConfig = new Configuration().Configure();
            _mapping = new MappingFactory().CreateMapping();
            _nhConfig.AddDeserializedMapping(_mapping, null);

            var sessionFactory = _nhConfig.BuildSessionFactory();
            _session = sessionFactory.OpenSession();
        }
Example #24
0
		public void ShouldAllowMappingComponentAsIdWithNestedClass()
		{
			var cfg = new Configuration();
			var mapper = new ModelMapper();
			mapper.Class<Entity>(rc => rc.ComponentAsId(entity => entity.Id, cid => cid.Property(p => p.Id)));

			var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
			cfg.AddDeserializedMapping(mapping, "TestDomain");
		}
Example #25
0
 /// <summary>
 ///     Configure from xml file
 /// </summary>
 /// <returns></returns>
 private static Configuration CreateConfiguration()
 {
     var configuration = new Configuration();
     configuration.Configure();
     Mapping = CreateMapping();
     configuration.AddDeserializedMapping(Mapping, null);
     SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
     return configuration;
 }
        public static Configuration AddAssemblyByCodeMap(this Configuration config, ModelMapper mapper, Assembly assembly)
        {
            assembly
            .CreateInstances <IModelMap>()
            .Each(x => x.Map(mapper));

            config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "CodeBy.hbm.xml");

            return(config);
        }
        private static Configuration CreateConfiguration()
        {
            var configuration = new Configuration();
            //Loads properties from hibernate.cfg.xml
            configuration.Configure();
            //Loads nhibernate mappings
            configuration.AddDeserializedMapping(Mapping, null);

            return configuration;
        }
Example #28
0
 public static ISession getSession()
 {
     var nhConfig = new Configuration().Configure();
     var mappingFactory = new MappingFactory();
     var mapper = mappingFactory.CreateMapping();
     nhConfig.AddDeserializedMapping(mapper, null);
     var sessionFactory = nhConfig.BuildSessionFactory();
     ISession _session = sessionFactory.OpenSession();
     return _session;
 }
Example #29
0
 public static ISessionFactory GetSessionFactory()
 {
     var config = new Configuration();
     config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using("Data source=nhtest.sqlite").AutoQuoteKeywords();
     var mapper = new ConventionModelMapper();
     Map(mapper);
     config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "Mappings");
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
     new SchemaUpdate(config).Execute(false, true);
     return config.BuildSessionFactory();
 }
        /// <summary>
        /// Should really only be used for unit tests
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TCodeMap"></typeparam>
        /// <param name="config"></param>
        /// <param name="codeMap"></param>
        /// <returns></returns>
        public static Configuration AddCodeMap <T, TCodeMap>(this Configuration config, TCodeMap codeMap)
            where T : ModelMapper, new()
            where TCodeMap : IModelMap, new()
        {
            var mapper = new T();
            var code   = new TCodeMap();

            code.Map(mapper);
            config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "Code.hbm.xml");
            return(config);
        }
Example #31
0
        static void Main(string[] args)
        {
            var mappingFactory = new MappingFactory();
              var mapping = mappingFactory.CreateMapping();

              var nhConfig = new Configuration().Configure();
              nhConfig.AddDeserializedMapping(mapping, null);

              var sessionFactory = nhConfig.BuildSessionFactory();
              Console.WriteLine("NHibernate configured!");
              Console.ReadKey();
        }
Example #32
0
 public static ISessionFactory GetSessionFactory()
 {
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
     var config = new Configuration();
     //config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using("Data source=nhtest.sqlite").AutoQuoteKeywords();
     config.SessionFactory().Integrate.Using<SQLiteDialect>().Connected.Using(String.Format("Data source={0}", Path.Combine(clientPath, "nhtest.sqlite"))).AutoQuoteKeywords();
     var mapper = new ConventionModelMapper();
     Map(mapper);
     config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "Mappings");
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
     new SchemaUpdate(config).Execute(false, true);
     return config.BuildSessionFactory();
 }
Example #33
0
        protected virtual void AddDefaultMapping(NHibernate.Cfg.Configuration cfg)
        {
            ModelMapper mm = new ModelMapper();

            mm.Class <ContentItem>(ContentItemCustomization);
            mm.Class <ContentDetail>(ContentDetailCustomization);
            mm.Class <DetailCollection>(DetailCollectionCustomization);
            mm.Class <AuthorizedRole>(AuthorizedRoleCustomization);

            var compiledMapping = mm.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddDeserializedMapping(compiledMapping, "N2");
        }
 static Store()
 {
     _cfg = new Configuration();
        // _cfg.Configure();
     _cfg.DataBaseIntegration(x =>
     {
         x.ConnectionString = "Server=.;Initial Catalog=UtbildningDatabas;Integrated Security=true;";
         x.Driver<SqlClientDriver>();
         x.Dialect<MsSql2012Dialect>();
     });
     _cfg.AddDeserializedMapping(CreateMapping(), null);
     //_cfg.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly());
 }
Example #35
0
        public void ExportSchema()
        {
            // Inicio do Setup do NH
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
                {
                    db.Dialect<MsSql2008Dialect>();
                    db.ConnectionStringName = "DefaultNH";
                    db.SchemaAction = SchemaAutoAction.Recreate;
                });

            ModelMapper modelMapper = new ModelMapper();

            modelMapper.AddMapping<ProdutoNHMap>();
            modelMapper.AddMapping<DepartamentoNHMap>();

            config.AddDeserializedMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities(), "Domain");

            ISessionFactory sessionFactory = config.BuildSessionFactory();

            // Fim do Setup do NH - Isso deve ficar no start da app (Global.asax por exemplo)

            using (var session = sessionFactory.OpenSession())
            {
                // Criteria API
                // HQL
                // Linq

                var produtosAcima1000 = session.QueryOver<Produto>().List();

                foreach (var produto in produtosAcima1000)
                {
                    Console.WriteLine(produto);
                }
            }

            using (var session = sessionFactory.OpenSession())
            {
                var produto = new Produto();

                produto.Nome = "Teste #1";
                produto.Preco = 90;
                produto.Quantidade = 123;
                produto.Ativo = true;

                session.Save(produto);
                session.Flush();
            }
        }
Example #36
0
        public void TestConfigMappingByCode()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

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

            var factory = config.BuildSessionFactory();

        }
Example #37
0
        public void TestConfigMappingByCode()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

            var factory = config.BuildSessionFactory();
        }
Example #38
0
        public void ConfigureHibernateMapping()
        {
            NHibernate.Cfg.Configuration hibernateConfig = (UnitOfWork.UnitOfWorkFactory as NHibernateUnitOfWorkFactory).Configuration;
            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(ProductModelMap).Assembly.GetExportedTypes());
            mapper.AddMappings(typeof(DistributorModelMap).Assembly.GetExportedTypes());
            mapper.AddMappings(typeof(QrCodeModelMap).Assembly.GetExportedTypes());

            hibernateConfig.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "FertilizerPlantScheme");
            SchemaUpdate schema = new SchemaUpdate(hibernateConfig);

            schema.Execute(true, true);
        }
 public static ISessionFactory CreateSessionFactory()
 {
     var configuration = new Configuration();
     configuration.Configure();
     var mapper = new ModelMapper();
     mapper.AddMapping<FileMapping>();
     mapper.AddMapping<CinemaMapping>();
     mapper.AddMapping<LanguageMapping>();
     mapper.AddMapping<CompanyMapping>();
     configuration.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
     var factory = configuration.BuildSessionFactory();
     new SchemaUpdate(configuration).Execute(false, true);
     return factory;
 }
Example #40
0
        public ConfigurationFactory(DatabaseSettings settings)
        {
            _configuration = new Configuration()
                             .SetInterceptor(new TenantIdInterceptor(settings.TenantId))
                             .DataBaseIntegration(db =>
            {
                db.ConnectionString = settings.ConnectionString;
                db.Dialect <MsSql2012Dialect>();
                db.BatchSize = 100;
            });

            _configuration
            .AddFilterDefinition(new TenantIdDefinition(settings.TenantId));

            var mapping = GetMappings();

            _configuration.AddDeserializedMapping(mapping, "schema");
            SchemaMetadataUpdater.QuoteTableAndColumns(_configuration);
            new SchemaExport(_configuration).SetOutputFile(@"c:\temp\atxc_schema.ddl").Execute(false, false, false);
            _sessionFactoryBuilder = _configuration.BuildSessionFactory();
        }
Example #41
0
        public void InitNHibernate()
        {
            if (SessionFactory != null)
            {
                return;
            }

            string connectionString = @"Server = 172.21.70.40; Database = PraktykiWorkFlow; User Id = sa;Password = cdnxl1*";



            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration().DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.Driver <SqlClientDriver>();
                db.ConnectionString = connectionString;
            });
            ModelMapper mapper = new ModelMapper();

            mapper.AddMappings(new List <Type>()
            {
                typeof(MapUser),
                typeof(MapAttribute),
                typeof(MapDocument),
                typeof(MapFlowDefinition),
                typeof(MapListElement),
                typeof(MapPosition),
                typeof(MapStep),
                typeof(MapAccess),
                typeof(MapFlow),
                typeof(MapFlowExtension),
                typeof(MapTask)
            });

            config.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);

            NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.QuoteTableAndColumns(config);

            SessionFactory = config.BuildSessionFactory();
        }
Example #42
0
        /// <summary>Adds mappings to the configuration.</summary>
        /// <param name="cfg">The configuration to add the mappings to.</param>
        /// <param name="name">The resource name of the embedded resource.</param>
        protected virtual void AddMapping(NHibernate.Cfg.Configuration cfg, string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                using (Stream stream = GetStreamFromName(name))
                {
                    if (stream == null)
                    {
                        throw new ArgumentException("Could not read stream from embedded resource '" + name + "'", "name");
                    }

                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var mappingXml = reader.ReadToEnd();
                        mappingXml = FormatMapping(mappingXml);

                        var xmlReader       = new XmlTextReader(mappingXml, XmlNodeType.Document, null);
                        var mappingDocument = cfg.LoadMappingDocument(xmlReader, "N2");
                        cfg.AddDeserializedMapping(mappingDocument.Document, mappingDocument.Name);
                    }
                }
            }
        }
Example #43
0
        public void Compile(NHcfg.Configuration configuration)
        {
            var mapper = new ModelMapperWithNamingConventions();

            mapper.IsEntity((type, declared) => MappingHelper.IsEntity(type));
            mapper.IsRootEntity((type, declared) => MappingHelper.IsRootEntity(type));
            mapper.IsTablePerClass((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerClassHierarchy((type, declared) =>
            {
                var discriminator = MappingHelper.GetDiscriminatorColumn(type);
                return(!string.IsNullOrWhiteSpace(discriminator));
            });
            mapper.IsTablePerConcreteClass((type, declared) => false);

            mapper.IsOneToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(false);
                }

                return(declared || _defaultMapper.ModelInspector.IsOneToMany(mi));
            });

            mapper.IsManyToMany((mi, declared) =>
            {
                if (Attribute.IsDefined(mi, (typeof(ManyToManyAttribute))))
                {
                    return(true);
                }

                return(declared || _defaultMapper.ModelInspector.IsManyToAny(mi));
            });

            mapper.IsPersistentProperty((mi, declared) =>
            {
                if (!NhMappingHelper.IsPersistentProperty(mi))
                {
                    return(false);
                }

                return(_defaultMapper.ModelInspector.IsPersistentProperty(mi));
            });

            mapper.BeforeMapSubclass += (modelInspector, type, subclassCustomizer) =>
            {
                var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                subclassCustomizer.DiscriminatorValue(discriminatorValue);


                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null)
                {
                    if (string.IsNullOrWhiteSpace(joinPropAttribute.TableName))
                    {
                        throw new Exception($"{nameof(JoinedPropertyAttribute.TableName)} is mandatory for `{joinPropAttribute.GetType().Name}`, check class `{type.FullName}`");
                    }

                    if (subclassCustomizer is NMIMPL.SubclassMapper subclassMapper)
                    {
                        // add join with provided table name, all properties will be added using current conventions and placed to the corresponding group using SplitGroupId = TableName
                        subclassMapper.Join(joinPropAttribute.TableName, j =>
                        {
                            j.Table(joinPropAttribute.TableName);

                            j.Fetch(FetchKind.Join);

                            j.Key(k =>
                            {
                                k.Column("Id");
                            });
                        });
                    }
                }
            };

            mapper.SplitsFor((type, definedSplits) =>
            {
                var splits = definedSplits.ToList();

                if (type.Name.Contains("TestProcessConfiguration"))
                {
                }

                var joinPropAttribute = type.GetAttribute <JoinedPropertyAttribute>();
                if (joinPropAttribute != null && !splits.Contains(joinPropAttribute.TableName))
                {
                    splits.Add(joinPropAttribute.TableName);
                }

                return(splits);
            });

            mapper.IsTablePerClassSplit((definition, b) => true);

            mapper.BeforeMapElement += (modelInspector, member, collectionRelationElementCustomizer) =>
            {
            };

            mapper.BeforeMapProperty += (modelInspector, member, propertyCustomizer) =>
            {
                var propertyType = member.LocalMember.GetPropertyOrFieldType();

                var    columnName = MappingHelper.GetColumnName(member.LocalMember);
                string sqlType    = null;
                IType  columnType = null;

                if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                {
                    columnType = NHibernateUtil.DateTime;
                    sqlType    = "DateTime";
                }
                else
                if (member.LocalMember.GetAttribute <StringLengthAttribute>()?.MaximumLength == int.MaxValue)
                //if (Attribute.IsDefined(member.LocalMember, (typeof(StringClobAttribute))))
                {
                    columnType = NHibernateUtil.StringClob;
                    sqlType    = "nvarchar(max)";
                }

                if (columnType != null)
                {
                    propertyCustomizer.Type(columnType);
                }

                if (Attribute.GetCustomAttribute(member.LocalMember, typeof(ReadonlyPropertyAttribute), true) is ReadonlyPropertyAttribute readonlyAttribute)
                {
                    propertyCustomizer.Insert(readonlyAttribute.Insert);
                    propertyCustomizer.Update(readonlyAttribute.Update);
                }

                propertyCustomizer.Column(c =>
                {
                    c.Name(columnName);
                    if (!string.IsNullOrWhiteSpace(sqlType))
                    {
                        c.SqlType(sqlType);
                    }
                });
            };

            mapper.IsPersistentId((mi, d) =>
            {
                var isId = mi.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase);
                return(isId);
            });
            mapper.BeforeMapClass += (modelInspector, type, classCustomizer) =>
            {
                var tableName = MappingHelper.GetTableName(type);

                classCustomizer.Table(tableName);

                var imMutable = type.HasAttribute <ImMutableAttribute>(true);
                if (imMutable)
                {
                    classCustomizer.Mutable(false);
                }

                if (MappingHelper.IsEntity(type))
                {
                    try
                    {
                        var idProp = type.GetProperty("Id");
                        if (idProp != null)
                        // note: Id may be missing when entity has hand-written mapping but isn't derived from EntityWithTypedId<> (for example: NhIdentityUserLogin)
                        {
                            if (tableName.StartsWith("Abp") && (idProp.PropertyType == typeof(Int64) || idProp.PropertyType == typeof(int)))
                            {
                                // temporary map `Abp` tables without hilo
                                classCustomizer.Id(p =>
                                {
                                    p.Column("Id");
                                    p.Generator(NHGens.Identity);
                                });
                            }
                            else
                            {
                                var idColumn = idProp.GetAttribute <ColumnAttribute>()?.Name ?? "Id";

                                // get Id mapper
                                var idMapper = _idMapper.Invoke(idProp.PropertyType);
                                if (idMapper != null)
                                {
                                    classCustomizer.Id(p =>
                                    {
                                        idMapper.Invoke(p);
                                        p.Column(idColumn);
                                    });
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }

                var discriminatorColumn = MappingHelper.GetDiscriminatorColumn(type);
                if (!string.IsNullOrWhiteSpace(discriminatorColumn))
                {
                    classCustomizer.Discriminator(d =>
                    {
                        d.Column(discriminatorColumn);

                        if (MappingHelper.GetFilterUnknownDiscriminatorsFlag(type))
                        {
                            d.Force(true);
                        }
                    });

                    var discriminatorValue = MappingHelper.GetDiscriminatorValue(type);

                    classCustomizer.DiscriminatorValue(discriminatorValue);
                }

                // IMayHaveTenant support
                if (typeof(IMayHaveTenant).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("MayHaveTenant", m =>
                    {
                    });
                }

                // ISoftDelete support
                if (typeof(ISoftDelete).IsAssignableFrom(type))
                {
                    classCustomizer.Filter("SoftDelete", m =>
                    {
                    });
                }
            };

            mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) =>
            {
                string columnPrefix = MappingHelper.GetColumnPrefix(propertyPath.LocalMember.DeclaringType);

                var lazyAttribute = propertyPath.LocalMember.GetAttribute <LazyAttribute>(true);
                var lazyRelation  = lazyAttribute != null?lazyAttribute.GetLazyRelation() : _defaultLazyRelation;

                if (lazyRelation != null)
                {
                    map.Lazy(lazyRelation);
                }

                var foreignKeyAttribute = propertyPath.LocalMember.GetAttribute <ForeignKeyAttribute>(true);
                var foreignKeyColumn    = foreignKeyAttribute != null
                    ? foreignKeyAttribute.Name
                    : columnPrefix + propertyPath.LocalMember.Name + "Id";

                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading
                map.Column(foreignKeyColumn);

                var directlyMappedFk = propertyPath.LocalMember.DeclaringType?.GetProperty(foreignKeyColumn);

                if (foreignKeyColumn.ToLower() == "id" || directlyMappedFk != null)
                {
                    map.Insert(false);
                    map.Update(false);
                }

                var cascadeAttribute = propertyPath.LocalMember.GetAttribute <CascadeAttribute>(true);
                map.Cascade(cascadeAttribute?.Cascade ?? Cascade.Persist);
                map.Class(propertyPath.LocalMember.GetPropertyOrFieldType());
            };

            mapper.BeforeMapBag += (modelInspector, propertyPath, map) => {
                var inversePropertyAttribute = propertyPath.LocalMember.GetAttribute <InversePropertyAttribute>(true);
                if (inversePropertyAttribute != null)
                {
                    map.Key(keyMapper => keyMapper.Column(inversePropertyAttribute.Property));
                }
                else
                {
                    map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Id"));
                }

                map.Cascade(Cascade.All);
                map.Lazy(CollectionLazy.Lazy);

                var bagMapper = map as NMIMPL.BagMapper;

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);

                if (manyToManyAttribute != null)
                {
                    map.Cascade(Cascade.None);

                    if (!string.IsNullOrEmpty(manyToManyAttribute.Table))
                    {
                        map.Table(manyToManyAttribute.Table);
                    }

                    if (!string.IsNullOrEmpty(manyToManyAttribute.KeyColumn))
                    {
                        map.Key(keyMapper => keyMapper.Column(manyToManyAttribute.KeyColumn));
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.Where))
                    {
                        map.Where(manyToManyAttribute.Where);
                    }
                    if (!string.IsNullOrEmpty(manyToManyAttribute.OrderBy))
                    {
                        map.OrderBy(manyToManyAttribute.OrderBy);
                    }
                }
                else
                {
                    if (bagMapper != null && typeof(ISoftDelete).IsAssignableFrom(bagMapper.ElementType))
                    {
                        //TODO: Check IsDeletedColumn for Many-To-Many
                        map.Where($"{SheshaDatabaseConsts.IsDeletedColumn} = 0");
                    }
                }
            };

            mapper.BeforeMapManyToMany += (modelInspector, propertyPath, map) => {
                //map.NotFound(NotFoundMode.Ignore); disabled due to performance issues, this option breaks lazy loading

                var manyToManyAttribute = propertyPath.LocalMember.GetAttribute <ManyToManyAttribute>(true);
                if (manyToManyAttribute != null)
                {
                    if (!string.IsNullOrEmpty(manyToManyAttribute.ChildColumn))
                    {
                        map.Column(manyToManyAttribute.ChildColumn);
                    }
                }
            };

            foreach (var assembly in _assemblies)
            {
                var allTypes = !assembly.IsDynamic
                    ? assembly.GetExportedTypes()
                    : assembly.GetTypes();
                var allEntities = allTypes.Where(t => MappingHelper.IsEntity(t)).ToList();
                foreach (var entityType in allEntities)
                {
                    var classMapping = configuration.GetClassMapping(entityType);
                    if (classMapping == null)
                    {
                        _entitiesToMap.Add(entityType);
                    }
                }

                var mappingOverride = allTypes.Where(t => IsClassMapping(t) && !t.IsAbstract).ToList();
                foreach (var @override in mappingOverride)
                {
                    try
                    {
                        var entityType = GetEntityTypeByMapping(@override);

                        if (entityType.IsEntityType())
                        {
                            _defaultMapper.AddMapping(@override);
                            mapper.AddMapping(@override);

                            if (entityType != null && !entityType.IsAbstract && !_entitiesToMap.Contains(entityType))
                            {
                                _entitiesToMap.Add(entityType);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }

            // sort entity types by hierarchy
            _entitiesToMap = MappingHelper.SortEntityTypesByInheritance(_entitiesToMap);

            /* for debug
             * foreach (var ent in _entitiesToMap)
             * {
             *  try
             *  {
             *      var mapping1 = mapper.CompileMappingFor(new List<Type> { ent });
             *  }
             *  catch (Exception e)
             *  {
             *      throw;
             *  }
             * }
             */

            HbmMapping mapping = mapper.CompileMappingFor(_entitiesToMap);

            configuration.AddDeserializedMapping(mapping, "AutoMapping");

            LastCompiledXml = mapping.AsString();
        }