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


C# ModelMapper类代码示例

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


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

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

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

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

示例4: ApplyMappings

        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
开发者ID:james-wu,项目名称:NServiceBus.NHibernate,代码行数:7,代码来源:NHibernateOutboxStorage.cs

示例5: MapClassWithIdAndProperty

		public void MapClassWithIdAndProperty()
		{
			var mapper = new ModelMapper();
			mapper.Class<MyClass>(ca =>
			{
				ca.Id("id", map =>
				{
					map.Column("MyClassId");
					map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
				});
				ca.Version("version", map => { });
				ca.Property("something", map => map.Length(150));
			});
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });
			var hbmClass = hbmMapping.RootClasses[0];
			hbmClass.Should().Not.Be.Null();
			var hbmId = hbmClass.Id;
			hbmId.Should().Not.Be.Null();
			hbmId.name.Should().Be("id");
			hbmId.access.Should().Be("field");
			var hbmGenerator = hbmId.generator;
			hbmGenerator.Should().Not.Be.Null();
			[email protected]().Be("hilo");
			hbmGenerator.param[0].name.Should().Be("max_low");
			hbmGenerator.param[0].GetText().Should().Be("100");
			var hbmVersion = hbmClass.Version;
			hbmVersion.name.Should().Be("version");
			var hbmProperty = hbmClass.Properties.OfType<HbmProperty>().Single();
			hbmProperty.name.Should().Be("something");
			hbmProperty.access.Should().Be("field");
			hbmProperty.length.Should().Be("150");
		}
开发者ID:Ruhollah,项目名称:nhibernate-core,代码行数:32,代码来源:MappingOfPrivateMembersOnRootEntity.cs

示例6: PostProcessConfiguration

        protected override void PostProcessConfiguration(global::NHibernate.Cfg.Configuration config)
        {
            base.PostProcessConfiguration(config);

            if (FluentNhibernateMappingAssemblies != null)
            {
                // add any class mappings in the listed assemblies:
                var mapper = new ModelMapper();

                foreach (var asm in FluentNhibernateMappingAssemblies.Select(Assembly.Load))
                {
                    mapper.AddMappings(asm.GetTypes());
                }

                foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity())
                {
                    config.AddMapping(mapping);
                }

                foreach (string assemblyName in FluentNhibernateMappingAssemblies)
                {
                    config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
                }
            }
        }
开发者ID:ora11g,项目名称:NossonCore,代码行数:25,代码来源:FluentNHibernateLocalSessionFactoryObject.cs

示例7: GetMappings

		protected override HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();
			mapper.Class<Order>(rc =>
				{
					rc.Table("Orders");
					rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
					rc.Property(x => x.Name);
					rc.Set(x => x.OrderLines, m =>
						{
							m.Inverse(true);
							m.Key(k =>
								{
									k.Column("OrderId");
									k.NotNullable(true);
								});
							m.Cascade(Mapping.ByCode.Cascade.All.Include(Mapping.ByCode.Cascade.DeleteOrphans));
							m.Access(Accessor.NoSetter);
						}, m => m.OneToMany());
				});
			mapper.Class<OrderLine>(rc =>
				{
					rc.Table("OrderLines");
					rc.Id(x => x.Id, m => m.Generator(Generators.GuidComb));
					rc.Property(x => x.Name);
					rc.ManyToOne(x => x.Order, m => m.Column("OrderId"));
				});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:30,代码来源:Fixture.cs

示例8: GetMapping

 public static HbmMapping GetMapping()
 {
     var modelMapper = new ModelMapper();
     modelMapper.AddMappings(Assembly.GetAssembly(typeof(PeopleMap)).GetExportedTypes());
     HbmMapping mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
     return mapping;
 }
开发者ID:chenbojian,项目名称:cbjany,代码行数:7,代码来源:NhibernateCfg.cs

示例9: ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces

		public void ShouldProperlyMapComponentWhenMappingOnlyPartOfItInSomePlaces()
		{
			var mapper = new ModelMapper();
			mapper.Class<ClassWithComponents>(cm =>
			{
				cm.Component(x => x.Component1, c =>
				{
					c.Property(x => x.PropertyOne, p => p.Column("OnePropertyOne"));
				});

				cm.Component(x => x.Component2, c =>
				{
					c.Property(x => x.PropertyOne, p => p.Column("TwoPropertyOne"));
					c.Property(x => x.PropertyTwo, p => p.Column("TwoPropertyTwo"));
				});
			});

			//Compile, and get the component property in which we mapped only one inner property
			var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

			var component1PropertyMapping = (HbmComponent)mappings.RootClasses[0].Properties.Single(x => x.Name == "Component1");

			//There should be only one inner property in the mapping of this component
			// Note: take a look at how CURRENTLY the test fails with 1 expected vs 2, instead of vs 3. 
			//       This means that the "PropertyThree" property of the component that was never mapped, is not taken into account (which is fine).
			Assert.That(component1PropertyMapping.Items.Length, Is.EqualTo(1));
		}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:27,代码来源:FixtureByCode.cs

示例10: Setup

        public void Setup()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            var configuration = new global::NHibernate.Cfg.Configuration()
                .AddProperties(new Dictionary<string, string>
                {
                    { "dialect", dialect },
                    { global::NHibernate.Cfg.Environment.ConnectionString,connectionString }
                });

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

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

            SessionFactory = configuration.BuildSessionFactory();

            Session = SessionFactory.OpenSession();

            persister = new OutboxPersister
            {
                StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session),
                EndpointName = "TestEndpoint"
            };

        }
开发者ID:andrewq,项目名称:NServiceBus.NHibernate,代码行数:27,代码来源:InMemoryDBFixture.cs

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

示例12: GetMappings

		private HbmMapping GetMappings()
		{
			var mapper = new ModelMapper();

			mapper.BeforeMapClass += (mi, t, map) => map.Id(x => x.Generator(Generators.GuidComb));

			mapper.Class<Parent>(rc =>
			{
				rc.Id(p => p.Id);
				rc.Property(p => p.ParentCode, m => m.Unique(true));
				rc.Property(p => p.Name);
				rc.Bag(p => p.Children, m =>
				{
					m.Key(km => { km.Column(cm => cm.Name("ParentParentCode")); km.PropertyRef(pg => pg.ParentCode); });
					m.Inverse(true);
					m.Cascade(Mapping.ByCode.Cascade.Persist);
				}, rel => rel.OneToMany());
			});

			mapper.Class<Child>(rc =>
			{
				rc.Id(p => p.Id);
				rc.Property(p => p.Name);
				rc.ManyToOne<Parent>(p => p.Parent, m => { m.Column("ParentParentCode"); m.PropertyRef("ParentCode"); });
			});

			return mapper.CompileMappingForAllExplicitlyAddedEntities();
		}
开发者ID:NikGovorov,项目名称:nhibernate-core,代码行数:28,代码来源:FixtureByCode.cs

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

示例14: AddFromConfig

 private static void AddFromConfig(ModelMapper modelMapper, IList<Assembly> assemblies)
 {
    for (int i = 0; i < assemblies.Count; ++i)
    {
       modelMapper.AddMappings(assemblies[i].GetTypes());
    }
 }
开发者ID:michelelepri,项目名称:NHibernate.LoquaciousMappingConfig,代码行数:7,代码来源:ModelMapperExtend.cs

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


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