• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Cfg.Configuration类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中NHibernate.Cfg.Configuration的典型用法代码示例。如果您正苦于以下问题:C# Configuration类的具体用法?C# Configuration怎么用?C# Configuration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Configuration类属于NHibernate.Cfg命名空间,在下文中一共展示了Configuration类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: BuildConfiguration

        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);
        }
开发者ID:ghy,项目名称:ConfORMSample,代码行数:35,代码来源:ConfORMConfigBuilder.cs


示例2: NHibernateSessionFactoryProvider

 protected NHibernateSessionFactoryProvider(IEnumerable<Type> mappedTypes,
     Action<IDbIntegrationConfigurationProperties> databaseIntegration)
 {
     _mappedTypes = mappedTypes;
     _databaseIntegration = databaseIntegration;
     _configuration = CreateConfiguration();
 }
开发者ID:StuartBaker65,项目名称:Automatonymous,代码行数:7,代码来源:NHibernateSessionFactoryProvider.cs


示例3: CreateConfiguration

 /// <summary>
 /// Creates a NHibernate configuration object containing mappings for this model.
 /// </summary>
 /// <returns>A NHibernate configuration object containing mappings for this model.</returns>
 public static Configuration CreateConfiguration()
 {
     var configuration = new Configuration();
       configuration.Configure();
       ApplyConfiguration(configuration);
       return configuration;
 }
开发者ID:Maharba,项目名称:LittleBooks,代码行数:11,代码来源:Libros.cs


示例4: Init

 private static void Init()
 {
     nhConfiguration = new Configuration();
     //nhConfiguration.Configure("NhibernateUtils/NHibernate.cfg.xml");
     nhConfiguration.AddAssembly("Activos");
     sessionFactory = nhConfiguration.BuildSessionFactory();
 }
开发者ID:kelvin088,项目名称:Activos,代码行数:7,代码来源:NHConnection.cs


示例5: BuildSchema

 private static void BuildSchema(Configuration configuration)
 {
     // this NHibernate tool takes a configuration (with mapping info in)
     // and exports a database schema from it
     new SchemaExport(configuration)
       .Create(false, true);
 }
开发者ID:avraax,项目名称:www.xbmcguide.dk,代码行数:7,代码来源:NHibernateHelper.cs


示例6: createConfiguration

 private Configuration createConfiguration()
 {
     Configuration cfg = new Configuration();
     cfg.Configure();
     cfg.AddAssembly(typeof(Mesto).Assembly);
     return cfg;
 }
开发者ID:stankela,项目名称:clanovi,代码行数:7,代码来源:PersistentConfigurationBuilder.cs


示例7: InitNHibernate

        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();
                }
            }
        }
开发者ID:SergeyMironchuk,项目名称:NHibernateStudy,代码行数:35,代码来源:NHibernateHelper.cs


示例8: Initialize

        public static Configuration Initialize()
        {
            INHibernateConfigurationCache cache = new NHibernateConfigurationFileCache();

            var mappingAssemblies = new[] {
                typeof(ActionConfirmation<>).Assembly.GetName().Name
            };

            var configuration = cache.LoadConfiguration(CONFIG_CACHE_KEY, null, mappingAssemblies);

            if (configuration == null) {
                configuration = new Configuration();

                configuration
                    .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                    .DataBaseIntegration(db => {
                        db.ConnectionStringName = "DonSharpLiteConnectionString";
                        db.Dialect<MsSql2008Dialect>();
                    })
                    .AddAssembly(typeof(ActionConfirmation<>).Assembly)
                    .CurrentSessionContext<LazySessionContext>();

                var mapper = new ConventionModelMapper();
                mapper.WithConventions(configuration);

                cache.SaveConfiguration(CONFIG_CACHE_KEY, configuration);
            }

            return configuration;
        }
开发者ID:antgerasim,项目名称:DonSharpArchitecture,代码行数:30,代码来源:NHibernateInitializer.cs


示例9: Process

		public override void Process(Configuration config)
		{
			var tables = GetTables(config);

			// create a resource resolver that will scan all plugins
			// TODO: we should only scan plugins that are tied to the specified PersistentStore, but there is currently no way to know this
			IResourceResolver resolver = new ResourceResolver(
				CollectionUtils.Map(Platform.PluginManager.Plugins, (PluginInfo pi) => pi.Assembly).ToArray());

			// find all dbi resources
			var rx = new Regex("dbi.xml$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
			var dbiFiles = resolver.FindResources(rx);

			foreach (var dbiFile in dbiFiles)
			{
				using (var stream = resolver.OpenResource(dbiFile))
				{
					var xmlDoc = new XmlDocument();
					xmlDoc.Load(stream);
					var indexElements = xmlDoc.SelectNodes("indexes/index");
					if (indexElements == null)
						continue;

					foreach (XmlElement indexElement in indexElements)
					{
						ProcessIndex(indexElement, tables);
					}
				}
			}

		}
开发者ID:nhannd,项目名称:Xian,代码行数:31,代码来源:AdditionalIndexProcessor.cs


示例10: When

		protected override void When()
		{
			this.configuration = FluentSearch.Configure()
				.Listeners(ListenerConfiguration.Custom
				           	.PostInsert(listener))
				.BuildConfiguration();
		}
开发者ID:najeraz,项目名称:Fluent-NHibernate-Search,代码行数:7,代码来源:Custom.cs


示例11: AddNHibernateSessionFactory

        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());
        }
开发者ID:csokun,项目名称:WebApiNHibernate,代码行数:25,代码来源:NHibernateSessionFactory.cs


示例12: CreateSessionFactory

        /// <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();
        }
开发者ID:AndyCC,项目名称:Jumbleblocks-website,代码行数:39,代码来源:DatabaseSetup.cs


示例13: CargarListas

        /// <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();
        }
开发者ID:powerponch,项目名称:LaModisteria,代码行数:28,代码来源:NotasDelClienteForm.xaml.cs


示例14: ReaderFactory

        /// <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);
            }
        }
开发者ID:PublicHealthEngland,项目名称:fingertips-open,代码行数:40,代码来源:ReaderFactory.cs


示例15: OracleSessionFactoryHelper

 static OracleSessionFactoryHelper()
 {
     var cfg = new Configuration();
     cfg.SessionFactory()
            .Proxy
                .DisableValidation()
                .Through<NHibernate.Bytecode.DefaultProxyFactoryFactory>()
                .Named("Fluent.SessionFactory")
                .GenerateStatistics()
                .Using(EntityMode.Poco)
                .ParsingHqlThrough<NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory>()
            .Integrate
                .Using<Oracle10gDialect>()
                .AutoQuoteKeywords()
                .LogSqlInConsole()
                .EnableLogFormattedSql()
            .Connected
                .Through<DriverConnectionProvider>()
                .By<OracleDataClientDriver>()
                .ByAppConfing("ConnectionString")
            .CreateCommands
                .Preparing()
                .WithTimeout(10)
                .AutoCommentingSql()
                .WithMaximumDepthOfOuterJoinFetching(11)
                .WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'");
     SessionFactory = FluentNHibernate.Cfg.Fluently.Configure(cfg)
            .Database(OracleDataClientConfiguration.Oracle10.ShowSql())
            .Mappings(m => GetMappingsAssemblies().ToList()
                .ForEach(o => m.FluentMappings.AddFromAssembly(o))).BuildSessionFactory();
 }
开发者ID:chenchunwei,项目名称:Infrastructure,代码行数:31,代码来源:OracleSessionFactoryHelper.cs


示例16: TestFixtureSetUp

 public void TestFixtureSetUp()
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Product).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
开发者ID:tasluk,项目名称:hibernatingrhinos,代码行数:7,代码来源:ProductRepository_Fixture.cs


示例17: TestClassSetup

 public static void TestClassSetup(TestContext context)
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Draft).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
开发者ID:Snidd,项目名称:RotisserieDraft,代码行数:7,代码来源:TestMemberRepository.cs


示例18: SpecifiedForeignKeyNameInByCodeMappingIsUsedInGeneratedSchema

		public void SpecifiedForeignKeyNameInByCodeMappingIsUsedInGeneratedSchema()
		{
			var mapper = new ModelMapper();

			// Generates a schema in which a Person record cannot be created unless an Employee
			// with the same primary key value already exists. The Constrained property of the
			// one-to-one mapping is required to create the foreign key constraint on the Person
			// table, and the optional ForeignKey property is used to name it; otherwise a
			// generated name is used

			mapper.Class<Person>(rc =>
			{
				rc.Id(x => x.Id, map => map.Generator(Generators.Foreign<Employee>(p => p.Person)));
				rc.Property(x => x.Name);
				rc.OneToOne(x => x.Employee, map =>
				{
					map.Constrained(true);
					map.ForeignKey(ForeignKeyName);
				});
			});

			mapper.Class<Employee>(rc =>
			{
				rc.Id(x => x.Id);
				rc.OneToOne(x => x.Person, map => { });
			});

			var script = new StringBuilder();
			var cfg = new Configuration();
			cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

			new SchemaExport(cfg).Execute(s => script.AppendLine(s), false, false);
			script.ToString().Should().Contain(string.Format("constraint {0}", ForeignKeyName));
		}
开发者ID:owerkop,项目名称:nhibernate-core,代码行数:34,代码来源:Fixture.cs


示例19: GetCfg

        public global::NHibernate.Cfg.Configuration GetCfg(string[] addAssemblies)
        {
            SessionFactoryImpl sessionFactoryImpl = SpringHelper.ApplicationContext["NHibernateSessionFactory"] as SessionFactoryImpl;
            IDictionary springObjectDic = getSpringObjectPropertyValue("NHibernateSessionFactory", "HibernateProperties") as IDictionary;
            IDictionary<string, string> dic = new Dictionary<string, string>();
            foreach (DictionaryEntry de in springObjectDic)
            {
                dic.Add(de.Key.ToString(), de.Value.ToString());
                //if (de.Key.ToString().Equals("hibernate.dialect"))
                //{
                //    dialectName = de.Value.ToString();
                //}
            }

            #region //真正抓取設定檔的內容
            ISession session = sessionFactoryImpl.OpenSession();
            string connectionStr = session.Connection.ConnectionString;
            #endregion

            dic.Add("connection.connection_string", connectionStr);
            Configuration cfg = new Configuration();
            cfg.AddProperties(dic);

            foreach (string assembly in addAssemblies)
            {
                cfg.AddAssembly(assembly);
            }

            return cfg;
        }
开发者ID:dada2cindy,项目名称:my-case-petemobile,代码行数:30,代码来源:TestHelper.cs


示例20: ExecuteStatement

        public int ExecuteStatement(string sql)
        {
            if (cfg == null)
            {
                cfg = new Configuration();
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                IDbConnection conn = prov.GetConnection();

                try
                {
                    using (IDbTransaction tran = conn.BeginTransaction())
                    using (IDbCommand comm = conn.CreateCommand())
                    {
                        comm.CommandText = sql;
                        comm.Transaction = tran;
                        comm.CommandType = CommandType.Text;
                        int result = comm.ExecuteNonQuery();
                        tran.Commit();
                        return result;
                    }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
开发者ID:jdaigle,项目名称:ProfilerBreakingTest,代码行数:30,代码来源:TestCase.cs



注:本文中的NHibernate.Cfg.Configuration类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# MappingSchema.HbmId类代码示例发布时间:2022-05-26
下一篇:
C# Cache.CacheKey类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap