当前位置: 首页>>代码示例>>C#>>正文


C# Configuration.AddMapping方法代码示例

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


在下文中一共展示了Configuration.AddMapping方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Initialize

        public static void Initialize(TestContext context)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x => {
                x.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=kmn23po;";
                x.Driver<MySqlDataDriver>();
                x.Dialect<MySQLDialect>();
                x.LogSqlInConsole = true;
                x.BatchSize = 30;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<ParentMap>();
            mapper.AddMapping<ParentWithGuidMap>();
            mapper.AddMapping<ChildMap>();

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = cfg.BuildSessionFactory();

            var schemaUpdate = new SchemaUpdate(cfg);
            schemaUpdate.Execute(false, true);

            InsertData();
        }
开发者ID:jplindgren,项目名称:NHibernateCodeCheat,代码行数:25,代码来源:UnitTest1.cs

示例2: AppDomainFactory

 public static ISessionFactory AppDomainFactory()
 {
     if (_appDomainFactory == null)
     {
         lock (_synRoot3)
         {
             if (_appDomainFactory == null)
             {
                 var createSchema = false;
                 var configuration = new Configuration()
                     .DataBaseIntegration(d =>
                     {
                         d.ConnectionStringName = Constants.APP_DB;
                         d.Dialect<MsSql2012Dialect>();
                         //d.Dialect<Oracle10gDialect>();
                         d.SchemaAction = SchemaAutoAction.Validate;
                     })
                     .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                     .CurrentSessionContext<LazySessionContext>()
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none")
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, (createSchema == true) ? SchemaAutoAction.Update.ToString() : SchemaAutoAction.Validate.ToString());
                 configuration.AddMapping(GetAppMappings());
                 configuration.BuildMapping();
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY]));
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App]));
                 //new NHibernate.Tool.hbm2ddl.SchemaExport(configuration).SetOutputFile(@"c:\temp\MyDDL.sql").Execute(true /*script*/, true /*export to db*/, false /*just drop*/);
                 _appDomainFactory = configuration.BuildSessionFactory();
             }
         }
     }
     return _appDomainFactory;
 }
开发者ID:jmptrader,项目名称:WebFrameworkMVC,代码行数:34,代码来源:NHibernateConfig.cs

示例3: NHibernateConfiguration

        public static void NHibernateConfiguration(TestContext context)
        {
            log4net.Config.XmlConfigurator.Configure();

            Configuration = new Configuration();
            // lendo o arquivo hibernate.cfg.xml
            Configuration.Configure();

            FilterDefinition filterDef = new FilterDefinition(
                "Empresa","EMPRESA = :EMPRESA",
                new Dictionary<string, IType>() {{"EMPRESA", NHibernateUtil.Int32}}, false);
            Configuration.AddFilterDefinition(filterDef);
            filterDef = new FilterDefinition(
                "Ativa", "ATIVO = 'Y'",
                new Dictionary<string, IType>(), false);
            Configuration.AddFilterDefinition(filterDef);

            // Mapeamento por código
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            Configuration.AddMapping(mapping);

            // Gerar o XML a partir do mapeamento de codigo.
            //var mappingXMl = mapping.AsString();

            // Mapeamento por arquivo, in resource.
            Configuration.AddAssembly(Assembly.GetExecutingAssembly());

            // Gerando o SessionFactory
            SessionFactory = Configuration.BuildSessionFactory();
        }
开发者ID:hrickmachado,项目名称:Crowdlearning-Tecnologia-NHibernate,代码行数:32,代码来源:Context.cs

示例4: BuildSessionFactory

        private ISessionFactory BuildSessionFactory()
        {
            var mapper = new ModelMapper();
            var configuration = new Configuration();

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

            configuration.DataBaseIntegration(c =>
            {
                c.ConnectionString = _connectionString;
                c.IsolationLevel = IsolationLevel.ReadCommitted;
                c.Driver<Sql2008ClientDriver>();
                c.Dialect<MsSql2008Dialect>();
                c.BatchSize = 50;
                c.Timeout = 30;

            #if DEBUG
                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;
                c.AutoCommentSql = true;
            #endif
            });

            #if DEBUG
            configuration.SessionFactory().GenerateStatistics();
            #endif

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            var sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory;
        }
开发者ID:prabuw,项目名称:NHibernateTemplate,代码行数:32,代码来源:SessionFactoryFactory.cs

示例5: BuildConfiguration

        public static Configuration BuildConfiguration(string connStr)
        {
            var cfg = new Configuration();

            // See http://fabiomaulo.blogspot.com/2009/07/nhibernate-configuration-through.html
            cfg.DataBaseIntegration(db => {
                db.Driver<SqlClientDriver>();
                db.Dialect<MsSql2012Dialect>();
                db.ConnectionString = connStr; // db.ConnectionStringName = "ConnStr";
                db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";

                // See http://geekswithblogs.net/lszk/archive/2011/07/12/showing-a-sql-generated-by-nhibernate-on-the-vs-build-in.aspx
                //db.LogSqlInConsole = true; // Remove if using Log4Net
                //db.LogFormattedSql = true;
                //db.AutoCommentSql = true;

                db.SchemaAction = SchemaAutoAction.Validate; // This correspond to "hbm2ddl.validate", see http://nhforge.org/blogs/nhibernate/archive/2008/11/23/nhibernate-hbm2ddl.aspx
            });

            var mapper = new ModelMapper();
            mapper.Class<Parent>(map => {
                map.Id(x => x.Id, m => {
                    m.Generator(Generators.GuidComb);
                    m.UnsavedValue(Guid.Empty);
                });
                map.Version(x => x.RowVersion, m => m.UnsavedValue(0));
                map.Property(x => x.Description);
            });
            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            return cfg;
        }
开发者ID:gimmi,项目名称:randomhacking,代码行数:31,代码来源:NHibernateConfigurator.cs

示例6: AzureSubcriptionStorage

        /// <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;
        }
开发者ID:remogloor,项目名称:NServiceBus,代码行数:43,代码来源:ConfigureNHibernateAzureSubscriptionStorage.cs

示例7: GetConfiguration

 private static Configuration GetConfiguration()
 {
     var config = new Configuration();
     config.Configure();
     config.AddMapping(GetMappings());
     return config;
 }
开发者ID:nothingmn,项目名称:BrockAllen.MembershipReboot,代码行数:7,代码来源:NhibernateConfig.cs

示例8: BuildProjectsSessionFactory

        private ISessionFactory BuildProjectsSessionFactory()
        {
            // register nhibernate
            var file = "deal.cat";
            if (ChiffrageWPF.Properties.Settings.Default.DealsRecentPath != null && ChiffrageWPF.Properties.Settings.Default.DealsRecentPath.Count > 0)
            {
                file = ChiffrageWPF.Properties.Settings.Default.DealsRecentPath[ChiffrageWPF.Properties.Settings.Default.DealsRecentPath.Count - 1];
            }

            var dealConfiguration = new Configuration()
            .Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>())
            .DataBaseIntegration(d =>
            {
                d.ConnectionString = string.Format("Data Source={0};Version=3;", file);
                d.Dialect<SQLiteDialect>();
                d.SchemaAction = SchemaAutoAction.Update;
            });
            var dealMapper = new ModelMapper();

            dealMapper.AddMappings(typeof(DealRepository).Assembly.GetTypes());

            HbmMapping dealMapping = dealMapper.CompileMappingForAllExplicitlyAddedEntities();
            dealConfiguration.AddMapping(dealMapping);

            return dealConfiguration.BuildSessionFactory();
        }
开发者ID:grozeille,项目名称:chiffrage,代码行数:26,代码来源:NHibernateModule.cs

示例9: Mapping

		protected override void Mapping(Configuration config)
		{
			var mapper = new ModelMapper();
			mapper.Class<Software>(map =>
			{
				map.Id(s => s.Id, o => o.Generator(Generators.GuidComb));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			mapper.Class<AssignedSoftware>(map =>
			{
				map.Id(s => s.Key, o => o.Generator(Generators.Assigned));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
			config.AddMapping(mapping);
			config.DataBaseIntegration(db => db.LogSqlInConsole = true);
		}
开发者ID:mzywitza,项目名称:Monastry.ActiveRecord,代码行数:27,代码来源:NhDaoFunctionalTests.cs

示例10: SessionFactory

        static SessionFactory()
        {
            var connectionString = @"Data Source=.\sqlexpress2014;Initial Catalog=BlogDatabase;Integrated Security=True";

            var configuration = new Configuration();
            configuration.DataBaseIntegration(
                x =>
                {
                    x.ConnectionString = connectionString;
                    x.Driver<SqlClientDriver>();
                    x.Dialect<MsSql2012Dialect>();
                });
            configuration.SetProperty(Environment.UseQueryCache, "true");
            configuration.SetProperty(Environment.UseSecondLevelCache, "true");
            configuration.SetProperty(Environment.CacheProvider, typeof(SysCacheProvider).AssemblyQualifiedName);
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            mapper.BeforeMapBag += (modelInspector, member1, propertyCustomizer) =>
            {
                propertyCustomizer.Inverse(true);
                propertyCustomizer.Cascade(Cascade.All | Cascade.DeleteOrphans);
            };
            mapper.BeforeMapManyToOne +=
                (modelInspector, member1, propertyCustomizer) => { propertyCustomizer.NotNullable(true); };
            mapper.BeforeMapProperty += (inspector, member, customizer) => customizer.NotNullable(true);
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            configuration.AddMapping(mapping);
            sessionFactory = configuration.BuildSessionFactory();
        }
开发者ID:Nerielle,项目名称:Learning,代码行数:30,代码来源:SessionFactory.cs

示例11: 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

示例12: TestConnection

        public void TestConnection()
        {
            var cfg = new Configuration()
                    .DataBaseIntegration(db =>
                    {
                        db.ConnectionString = "Server=127.0.0.1;Database=troyanda;Uid=postgres;Pwd=qwerty;";
                        db.Dialect<PostgreSQL94Dialect>();
                        db.SchemaAction = SchemaAutoAction.Validate;
                    });

            var types = typeof (Cars).Assembly.GetExportedTypes();
            /* Add the mapping we defined: */
            var mapper = new ModelMapper();
            mapper.AddMappings(types);

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            /* Create a session and execute a query: */
            using (ISessionFactory factory = cfg.BuildSessionFactory())
            using (ISession session = factory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                var car = session.Get<Cars>((long)1);

                var worker = new WorkerServices(cfg, session);

                var result = worker.GetItemsPresenterForEntity(typeof (Sector));
                //session.Save()

                tx.Commit();
            }
        }
开发者ID:AndreyRepko,项目名称:Dacha,代码行数:34,代码来源:BasicDataTest.cs

示例13: GenerateSchema

        public static void GenerateSchema()
        {
            Configuration cfg = new Configuration();

            //cfg.SetProperty("nhibernate.envers.default_schema", "audit");

            cfg.AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

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

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(mapping);

            cfg.AddAssembly(typeof(Model).Assembly);

            //cfg.IntegrateWithEnvers();

            cfg.Configure();

            new NHibernate.Tool.hbm2ddl.SchemaExport(cfg)
                .SetDelimiter(";")
                //.SetOutputFile("schema.sql")
                .Execute(false, true, false);
        }
开发者ID:rungwiroon,项目名称:NHibernate.Spatial,代码行数:25,代码来源:NHibernateHelper.cs

示例14: CreateSqlSchema

        public void CreateSqlSchema()
        {
            var sqlBuilder = new SqlConnectionStringBuilder();
              sqlBuilder.DataSource = "(local)";
              sqlBuilder.InitialCatalog = "nservicebus";
              sqlBuilder.IntegratedSecurity = true;

              var cfg = new Configuration()

            .DataBaseIntegration(x =>
                               {
                                 x.Dialect<MsSql2008Dialect>();
                                 x.ConnectionString = sqlBuilder.ConnectionString;
                               });

              var mapper = new ModelMapper();
              mapper.AddMappings(typeof(NHibernate.Config.SubscriptionMap).Assembly.GetExportedTypes());
              HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

              cfg.AddMapping(faultMappings);

              File.WriteAllText("schema.sql", "");

              new SchemaExport(cfg).Create(x => File.AppendAllText("schema.sql", x), true);

              subscriptionStorageSessionProvider = new SubscriptionStorageSessionProvider(cfg.BuildSessionFactory());

              storage = new SubscriptionStorage(subscriptionStorageSessionProvider);
        }
开发者ID:nghead,项目名称:NServiceBus,代码行数:29,代码来源:SqlServerFixture.cs

示例15: 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


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