/// <summary>
        /// Gets a mapping that can be used with NHibernate.
        /// </summary>
        /// <param name="additionalTypes">Additional Types that are to be added to the mapping, this is useful for adding your ApplicationUser class</param>
        /// <returns></returns>
        public static HbmMapping GetIdentityMappings(System.Type[] additionalTypes)
        {
            var baseEntityToIgnore = new[] { 
                typeof(NHibernate.AspNet.Identity.DomainModel.EntityWithTypedId<int>), 
                typeof(NHibernate.AspNet.Identity.DomainModel.EntityWithTypedId<string>), 
            };

            var allEntities = new List<System.Type> { 
                typeof(ApplicationTenant),
                typeof(IdentityUser),                 
                typeof(IdentityRole), 
                typeof(IdentityUserLogin), 
                typeof(IdentityUserClaim),
            };
            allEntities.AddRange(additionalTypes);

            var mapper = new ConventionModelMapper();
            DefineBaseClass(mapper, baseEntityToIgnore.ToArray());
            mapper.IsComponent((type, declared) => typeof(NHibernate.AspNet.Identity.DomainModel.ValueObject).IsAssignableFrom(type));

            mapper.AddMapping<IdentityUserMap>();
            mapper.AddMapping<IdentityRoleMap>();
            mapper.AddMapping<IdentityUserClaimMap>();
            mapper.AddMapping<ApplicationTenantMap>();

            return mapper.CompileMappingFor(allEntities);
        }
Example #2
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;
            }
         
        }
 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;
 }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MappingEngine"/> class
 /// </summary>
 /// <param name="rootConfig">The root configuration</param>
 /// <param name="nhConfig">The current NH configuration</param>
 /// <param name="modelMapper">The model mapper</param>
 public MappingEngine(FirehawkConfig rootConfig, Configuration nhConfig, ConventionModelMapper modelMapper)
 {
     this.rootConfig = rootConfig;
     this.nhConfig = nhConfig;
     this.modelMapper = modelMapper;
     this.namingEngine = new NamingEngine(rootConfig.NamingConventionsConfig);
 }
Example #5
0
        public ConventionsMapper()
        {
            this.conventionModelMapper = new ConventionModelMapper();

            var baseEntityType = typeof(Entity);
            this.conventionModelMapper.IsEntity((t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            this.conventionModelMapper.IsRootEntity((t, declared) => baseEntityType.Equals(t.BaseType));
            this.conventionModelMapper.Class<Entity>(map => {
                                                     	map.Id(x => x.Id, m => m.Generator(Generators.Identity));
                                                     	map.Id(x => x.Id, m => m.Column("id"));
                                                     	map.Version(x => x.Version, m => m.Generated(VersionGeneration.Always));
                                                     	map.Version(x => x.Version, m => m.Column("version"));
                                                     });

            this.conventionModelMapper.BeforeMapProperty += (insp, prop, map) => map.Column(prop.LocalMember.Name);

            this.conventionModelMapper.BeforeMapManyToOne += (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");
            this.conventionModelMapper.BeforeMapManyToOne += (insp, prop, map) => map.Cascade(Cascade.Persist);

            this.conventionModelMapper.BeforeMapBag += (insp, prop, map) => map.Table(prop.GetContainerEntity(insp).Name + prop.GetRootMember().Name);
            this.conventionModelMapper.BeforeMapBag += (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));
            this.conventionModelMapper.BeforeMapBag += (insp, prop, map) => map.Cascade(Cascade.All);

            this.conventionModelMapper.BeforeMapClass += (insp, prop, map) => map.Table(prop.Name);

            this.conventionModelMapper.AddMappings(typeof(RestaurantMappings).Assembly.GetTypes());
            this.mapping = this.conventionModelMapper.CompileMappingFor(baseEntityType.Assembly.GetExportedTypes().Where(t => t.Namespace != null && t.Namespace.EndsWith("Entities")));
        }
Example #6
0
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper)
 {
     foreach (var entity in entities)
     {
         var properties = entity.GetProperties(BindingFlags.Public | BindingFlags.Instance);
         foreach (var property in properties)
         {
             var propertyTypeToCheck = property.PropertyType;
             if (propertyTypeToCheck.DetermineCollectionElementOrDictionaryValueType() != null)
             {
                 continue;
             }
             if (entities.Contains(propertyTypeToCheck))
             {
                 continue;
             }
             if (property.CanWrite == false)
             {
                 var method = typeof(ReadOnlyConvention).GetMethod("MapReadOnly", BindingFlags.Public | BindingFlags.Static)
                              .MakeGenericMethod(new[] { property.DeclaringType, property.PropertyType });
                 method.Invoke(null, new object[] { mapper, property });
             }
         }
     }
 }
Example #7
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ConventionModelMapper();
			// Working Example
			//mapper.Class<Toy>(rc => rc.Set(x => x.Animals, cmap => { }, rel => rel.ManyToAny<int>(meta =>
			//                                                                                      {
			//                                                                                        meta.MetaValue(1, typeof (Cat));
			//                                                                                        meta.MetaValue(2, typeof (Dog));
			//                                                                                      })));

			// User needs
			mapper.Class<Toy>(rc => rc.Set(x => x.Animals, cmap =>
																										 {
																											 cmap.Table("Animals_Toys");
																											 cmap.Key(km => km.Column("Cat_Id"));
																										 }, rel => rel.ManyToAny<int>(meta =>
																																									{
																																										meta.MetaValue(1, typeof(Cat));
																																										meta.MetaValue(2, typeof(Dog));
																																										meta.Columns(cid =>
																																																 {
																																																	 cid.Name("Animal_Id");
																																																	 cid.NotNullable(true);
																																																 }, ctype =>
																																																		{
																																																			ctype.Name("Animal_Type");
																																																			ctype.NotNullable(true);
																																																		});
																																									})));
			var mappings = mapper.CompileMappingFor(new[] { typeof(Cat), typeof(Dog), typeof(Toy) });
			//Console.WriteLine(mappings.AsString()); // <=== uncomment this line to see the XML mapping
			return mappings;
		}
        static void Main(string[] args)
        {
            SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

            var mapper = new ConventionModelMapper();

            mapper.Class<SomeAreaClass>(c =>
            {
                c.Property(x => x.Area, m =>
                {
                    m.Type<MsSql2008GeographyType>();
                    m.NotNullable(true);
                });
            });

            var cfg = new Configuration()

                .DataBaseIntegration(db =>
                {
                    db.ConnectionString = "YourConnectionString";
                    db.Dialect<MsSql2012GeographyDialect>();
                });

            cfg
                .AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            cfg
                .AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

            new SchemaExport(cfg).Execute(false, true, false);
        }
		static void ExplicitMapping(ConventionModelMapper mapper)
		{
			mapper.Class<Master>(x =>
			{
				x.Id(y => y.Id, y => y.Generator(Generators.HighLow));
				x.Set(y => y.Options, y =>
				{
					y.Key(z => z.Column("master_id"));
					y.Table("master_option");
				}, y =>
				{
					y.ManyToMany(z =>
					{
						z.Column("option_id");
					});
				});
			});

			mapper.Class<Option>(x =>
			{
				x.Id(y => y.Id, y => y.Generator(Generators.HighLow));
				x.Set(y => y.Masters, y =>
				{
					y.Key(z => z.Column("option_id"));
					y.Table("master_option");
					y.Inverse(true);
				}, y =>
				{
					y.ManyToMany(z =>
					{
						z.Column("master_id");
					});
				});
			});
		}
        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;
        }
Example #11
0
        protected override void CallGenericRelationMethod(NHibernate.Mapping.ByCode.ConventionModelMapper mapper, System.Reflection.PropertyInfo property, System.Reflection.PropertyInfo inverseProperty)
        {
            var method = typeof(BidirectionalOneToManyConvention).GetMethod("MapOneToMany", BindingFlags.Public | BindingFlags.Static)
                         .MakeGenericMethod(new[] { property.DeclaringType, inverseProperty.DeclaringType });

            method.Invoke(null, new object[] { mapper, property, inverseProperty });
        }
Example #12
0
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper)
 {
     mapper.Class <Entity>(map =>
     {
         map.Version("Version", m => m.Generated(VersionGeneration.Never));
     });
 }
        public static void Configure(ISessionStorage storage)
        {
            var baseEntityToIgnore = new[] { 
                typeof(NHibernate.AspNet.Identity.DomainModel.EntityWithTypedId<int>), 
                typeof(NHibernate.AspNet.Identity.DomainModel.EntityWithTypedId<string>), 
            };

            var allEntities = new[] { 
                typeof(IdentityUser), 
                typeof(ApplicationUser), 
                typeof(IdentityRole), 
                typeof(IdentityUserLogin), 
                typeof(IdentityUserClaim), 
            };

            var mapper = new ConventionModelMapper();
            DefineBaseClass(mapper, baseEntityToIgnore);
            mapper.IsComponent((type, declared) => typeof(NHibernate.AspNet.Identity.DomainModel.ValueObject).IsAssignableFrom(type));

            mapper.AddMapping<IdentityUserMap>();
            mapper.AddMapping<IdentityRoleMap>();
            mapper.AddMapping<IdentityUserClaimMap>();

            var mapping = mapper.CompileMappingFor(allEntities);
            System.Diagnostics.Debug.WriteLine(mapping.AsString());

            var configuration = NHibernateSession.Init(storage, mapping);
            BuildSchema(configuration);
        }
Example #14
0
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper)
 {
     mapper.BeforeMapClass += (modelInspector, type, map) =>
     {
         PluralizeEntityName(type, map);
         PrimaryKeyConvention(type, map);
     };
     mapper.BeforeMapClass            += MakeNotLazy;
     mapper.BeforeMapManyToOne        += ReferenceConvention;
     mapper.BeforeMapBag              += OneToManyConvention;
     mapper.BeforeMapManyToMany       += ManyToManyConvention;
     mapper.BeforeMapJoinedSubclass   += MapJoinedSubclass;
     mapper.BeforeMapAny              += MapAny;
     mapper.BeforeMapComponent        += MapComponent;
     mapper.BeforeMapElement          += MapElement;
     mapper.BeforeMapIdBag            += MapIdBag;
     mapper.BeforeMapList             += MapList;
     mapper.BeforeMapMap              += MapMap;
     mapper.BeforeMapMapKey           += MapMapKey;
     mapper.BeforeMapMapKeyManyToMany += MapMapKeyManyToMany;
     mapper.BeforeMapOneToMany        += MapOneToMany;
     mapper.BeforeMapOneToOne         += MapOneToOne;
     mapper.BeforeMapProperty         += MapProperty;
     mapper.BeforeMapSet              += MapSet;
     mapper.BeforeMapSubclass         += MapSubclass;
     mapper.BeforeMapUnionSubclass    += MapUnionSubclass;
     mapper.BeforeMapProperty         += ReadOnlyConvention;
 }
Example #15
0
        /// <summary>
        /// Gets a mapping that can be used with NHibernate.
        /// </summary>
        /// <param name="additionalTypes">Additional Types that are to be added to the mapping, this is useful for adding your ApplicationUser class</param>
        /// <returns></returns>
        public static HbmMapping GetIdentityMappings(System.Type[] additionalTypes)
        {
            var baseEntityToIgnore = new[]
            {
                typeof(EntityWithTypedId<int>),
                typeof(EntityWithTypedId<string>)
            };

            // Modified for NS: PIMS.Infrastructure.NHibernate.NHAspNetIdentity
            var allEntities = new List<System.Type> {
                typeof(IdentityUser),
                typeof(IdentityRole),
                typeof(IdentityUserLogin),
                typeof(IdentityUserClaim),
            };
            allEntities.AddRange(additionalTypes);

            var mapper = new ConventionModelMapper();
            DefineBaseClass(mapper, baseEntityToIgnore.ToArray());
            mapper.IsComponent((type, declared) => typeof(ValueObject).IsAssignableFrom(type));

               // Modified for NS: PIMS.Infrastructure.NHibernate.NHAspNetIdentity
            mapper.AddMapping<IdentityUserMap>();
            mapper.AddMapping<IdentityRoleMap>();
            mapper.AddMapping<IdentityUserClaimMap>();

            return mapper.CompileMappingFor(allEntities);
        }
 protected override void CustomizeMapping(ConventionModelMapper mapper)
 {
     mapper.Class<Foo>(cm => cm.List(x => x.Bars, bpm =>
                                                  {
                                                      bpm.Cascade(Cascade.All);
                                                      bpm.Type<PersistentQueryableListType<Bar>>();
                                                  }));
 }
Example #17
0
		protected override HbmMapping GetMappings()
		{
			var mapper = new ConventionModelMapper();
			mapper.IsTablePerClass((type, declared) => false);
			mapper.IsTablePerClassHierarchy((type, declared) => true);
			var mappings = mapper.CompileMappingFor(new[] {typeof (Animal), typeof (Reptile), typeof (Mammal), typeof (Lizard), typeof (Dog), typeof (Cat)});
			return mappings;
		}
Example #18
0
		public void WhenPoidNoSetterThenApplyNosetter()
		{
			var mapper = new ConventionModelMapper();
			mapper.Class<MyClass>(x => x.Id(mc=> mc.Id));
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

			var hbmClass = hbmMapping.RootClasses[0];
			hbmClass.Id.access.Should().Be("nosetter.camelcase-underscore");
		}
Example #19
0
 private static void DefineBaseClass(ConventionModelMapper mapper, System.Type[] baseEntityToIgnore)
 {
     if (baseEntityToIgnore == null) return;
     mapper.IsEntity((type, declared) =>
         baseEntityToIgnore.Any(x => x.IsAssignableFrom(type)) &&
         !baseEntityToIgnore.Any(x => x == type) &&
         !type.IsInterface);
     mapper.IsRootEntity((type, declared) => baseEntityToIgnore.Any(x => x == type.BaseType));
 }
		public void WhenAutoPropertyNoAccessor()
		{
			var mapper = new ConventionModelMapper();
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmProperty = hbmClass.Properties.Single(x => x.Name == "AProp");
			hbmProperty.Access.Should().Be.NullOrEmpty();
		}
		public void WhenReadOnlyPropertyWithSameBackFieldNoMatch()
		{
			var mapper = new ConventionModelMapper();
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmProperty = hbmClass.Properties.Single(x => x.Name == "ReadOnlyWithSameBackField");
			Assert.That(hbmProperty.Access, Is.Not.StringContaining("field"));
		}
		public void WhenPropertyWithSameBackFieldNoMatch()
		{
			var mapper = new ConventionModelMapper();
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmProperty = hbmClass.Properties.Single(x => x.Name == "SameTypeOfBackField");
			hbmProperty.Access.Should().Be.NullOrEmpty();
		}
 protected override void CustomizeMapping(ConventionModelMapper mapper)
 {
     mapper.Class<Foo>(cm => cm.IdBag(x => x.Bars,
                                      bpm =>
                                      {
                                          bpm.Cascade(Cascade.All);
                                          bpm.Type<PersistentQueryableIdBagType<Bar>>();
                                      },
                                      cer => cer.ManyToMany()));
 }
		public void WhenFieldAccessToField()
		{
			var mapper = new ConventionModelMapper();
			mapper.Class<MyClass>(mc => mc.Property("aField", x => { }));
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmProperty = hbmClass.Properties.Single(x => x.Name == "aField");
			hbmProperty.Access.Should().Be("field");
		}
		static void Main(String[] args)
		{
			var cfg = new Configuration();
			cfg.DataBaseIntegration(x =>
				{
					x.Dialect<MsSql2008Dialect>();
					x.Driver<Sql2008ClientDriver>();
					x.ConnectionString = @"Data Source=(local)\SQLEXPRESS; Initial Catalog=NHibernate; Integrated Security=SSPI";
					x.SchemaAction = SchemaAutoAction.Update;
				})
				.SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString);

			var model = new ConventionModelMapper();
			model.BeforeMapClass += (a, b, c) => { c.Lazy(false); c.Id(x => x.Generator(Generators.Identity)); };

			var mappings = model.CompileMappingFor(new Type[] { typeof(Xpto) });

			cfg.AddMapping(mappings);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				var validation = sessionFactory
					.FluentlyValidate()
					.Entity<Xpto>(x => x.Name != "aa", "Name is empty");

				using (var session = sessionFactory.OpenSession())
				using (var tx = session.BeginTransaction())
				{
					var x = new Xpto();

					try
					{
						session.Save(x);
						session.Flush();
					}
					catch
					{
						//expected
					}

					x.Name = "aa";

					//disable all validations
					//sessionFactory.DisableFluentValidation();
					
					//disable validations over the Xpto class
					//validation.Clear<Xpto>();

					//session.Save(new Xpto());
					session.Flush();
					//should work
				}
			}
		}
Example #26
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>
        /// Looks through this assembly for any IOverride classes.  If found, it creates an instance
        /// of each and invokes the Override(mapper) method, accordingly.
        /// </summary>
        private static void AddConventionOverrides(ConventionModelMapper mapper) {
            Type overrideType = typeof(IOverride);
            List<Type> types = typeof(IOverride).Assembly.GetTypes()
                .Where(t => overrideType.IsAssignableFrom(t) && t != typeof(IOverride))
                .ToList();

            types.ForEach(t => {
                IOverride conventionOverride = Activator.CreateInstance(t) as IOverride;
                conventionOverride.Override(mapper);
            });
        }
Example #28
0
        static void AddConventionalMapping(Configuration cfg)
        {
            var modelMapper = new ConventionModelMapper();
            modelMapper.IsEntity((x, y) => x.IsClass == true && x.IsSealed == false && x.Namespace == typeof(Program).Namespace);
            modelMapper.BeforeMapClass += (x, y, z) => { z.Id(a => a.Generator(Generators.Identity)); z.Lazy(true); };
            modelMapper.BeforeMapManyToOne += (x, y, z) => { z.Lazy(LazyRelation.Proxy); z.NotNullable(true); };

            var mappings = modelMapper.CompileMappingFor(typeof(Program).Assembly.GetTypes().Where(x => x.IsPublic && x.IsSealed == false));

            cfg.AddMapping(mappings);
        }
        public static IConfigurationProvider CreateConfigurationProvider()
        {
            var configFilePath = PathHelpers.InCurrentAppDomain(Constants.NHibernateConfigFileName);
            var configuration = new Configuration();
            configuration.Configure(configFilePath);

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

            return new ConfigurationProvider(configuration);
        }
		protected override HbmMapping GetMappings()
		{
			var mapper = new ConventionModelMapper();
			mapper.BeforeMapClass += (inspector, type, map) => map.Id(x => x.Generator(Generators.HighLow));
			mapper.BeforeMapClass += (inspector, type, map) => map.Cache(x => x.Usage(CacheUsage.ReadWrite));
			mapper.BeforeMapSet += (inspector, property, map) =>
			                       {
			                       	map.Cascade(Mapping.ByCode.Cascade.All);
			                       	map.Cache(x => x.Usage(CacheUsage.ReadWrite));
			                       };
			var mapping = mapper.CompileMappingFor(new[] { typeof(Blog), typeof(Post), typeof(Comment) });
			return mapping;
		}
Example #31
0
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper, IEnumerable <Type> entities)
 {
     mapper.AfterMapClass          += EscapeAndMaybePluralizeEntityName;
     mapper.AfterMapClass          += PrimaryKeyConvention;
     mapper.AfterMapManyToOne      += ReferenceConvention;
     mapper.AfterMapSet            += OneToManyConvention;
     mapper.AfterMapBag            += OneToManyConvention;
     mapper.AfterMapList           += OneToManyConvention;
     mapper.AfterMapManyToMany     += ManyToManyConvention;
     mapper.AfterMapJoinedSubclass += MapJoinedSubclass;
     mapper.AfterMapProperty       += ComponentNamingConvention;
     mapper.AfterMapProperty       += EscapeColumnName;
 }
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
		public void WhenClassWithoutPoidNorGeeneratorThenApplyGuid()
		{
			var mapper = new ConventionModelMapper();
			mapper.Class<MyClassWithoutPoid>(x => { });
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClassWithoutPoid) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmId = hbmClass.Id;
			hbmId.Should().Not.Be.Null();
			hbmId.generator.Should().Not.Be.Null();
			[email protected]().Be("guid");
			hbmId.type1.Should().Be("Guid");
		}
Example #34
0
		public void WhenClassWithoutPoidWithGeneratorThenApplyDefinedGenerator()
		{
			var mapper = new ConventionModelMapper();
			mapper.Class<MyClassWithoutPoid>(x => x.Id(null, idm=> idm.Generator(Generators.Native)));
			var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClassWithoutPoid) });

			var hbmClass = hbmMapping.RootClasses[0];
			var hbmId = hbmClass.Id;
			hbmId.Should().Not.Be.Null();
			hbmId.generator.Should().Not.Be.Null();
			[email protected]().Be("native");
			hbmId.type1.Should().Be(Generators.Native.DefaultReturnType.GetNhTypeName());
		}
        public void CanGenerateMappingDoc()
        {
            // Need a separate config so we can get hold of the mapper after using it.
            // If we use the existing config we get a duplicate mapping exception.
            var config = NHibernateInitializer.CreateConfiguration();

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

            var mapping = mapper.CompileMappingFor(typeof(Entity).Assembly.GetExportedTypes());
            var x = mapping.AsString();
            File.WriteAllText("../../NHibernateTests/Output.xml", x);
        }
Example #36
0
        /// <summary>
        /// Looks through this assembly for any IOverride classes.  If found, it creates an instance
        /// of each and invokes the Override(mapper) method, accordingly.
        /// </summary>
        private static void AddConventionOverrides(ConventionModelMapper mapper)
        {
            var overrideType = typeof(IOverride);
            var types        = typeof(IOverride).Assembly.GetTypes()
                               .Where(t => overrideType.IsAssignableFrom(t) && t != typeof(IOverride))
                               .ToList();

            types.ForEach(t =>
            {
                var conventionOverride = Activator.CreateInstance(t) as IOverride;
                conventionOverride.Override(mapper);
            });
        }
        public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper)
        {
            var mappedItemsCache = new List <string>();

            foreach (var entity in entities)
            {
                var properties = entity.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var property in properties)
                {
                    this.ShouldProcess = false;
                    var propertyTypeToCheck = property.PropertyType;
                    if (propertyTypeToCheck.DetermineCollectionElementOrDictionaryValueType() != null)
                    {
                        propertyTypeToCheck = propertyTypeToCheck.GetGenericArguments()[0];
                    }
                    if (this.BaseEntityType != null && !propertyTypeToCheck.IsSubclassOf(this.BaseEntityType))
                    {
                        continue;
                    }
                    if (!this.entities.Contains(propertyTypeToCheck))
                    {
                        continue;
                    }
                    var inverseProperty = GetInverseProperty(property);//should return inverse property if conditions are met or return null otherwise
                    if ((inverseProperty != null && mappedItemsCache.Contains(inverseProperty.PropertyType.FullName + inverseProperty.Name + inverseProperty.DeclaringType.FullName)) || mappedItemsCache.Contains(property.PropertyType.FullName + property.Name + property.DeclaringType.FullName))
                    {
                        continue;
                    }
                    if (ShouldProcess)
                    {
                        CallGenericRelationMethod(mapper, property, inverseProperty);
                        if (inverseProperty != null)
                        {
                            mappedItemsCache.Add(inverseProperty.PropertyType.FullName + inverseProperty.Name + inverseProperty.DeclaringType.FullName);
                        }
                        mappedItemsCache.Add(property.PropertyType.FullName + property.Name + property.DeclaringType.FullName);
                    }
                }
            }
        }
 protected abstract void CallGenericRelationMethod(NHibernate.Mapping.ByCode.ConventionModelMapper mapper, PropertyInfo property, PropertyInfo inverseProperty);
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper)
 {
     mapper.BeforeMapProperty += mapProperty;
 }
Example #40
0
 public void ProcessMapper(NHibernate.Mapping.ByCode.ConventionModelMapper mapper, IEnumerable <Type> entities)
 {
     mapper.BeforeMapProperty += mapProperty;
 }
Example #41
0
        public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration)
        {
            var baseEntityType = typeof(Entity);

            mapper.IsEntity((type, declared) => IsEntity(type));
            mapper.IsComponent((type, b) => IsComponent(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.HighLow));
                classCustomizer.Table(Inflector.Net.Inflector.Pluralize(type.Name.ToString()));
            };

            mapper.IsPersistentProperty((memberinfo, currentlyPersistent) =>
            {
                return(memberinfo.Name != "Owner");
            });

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

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

            mapper.BeforeMapProperty += (inspector, member, customizer) => {
                // This is pure guesswork, but seems to be the only way I can think of to alter
                // the column naming of a property mapped as part of a component
                if (typeof(IComponent).IsAssignableFrom(member.LocalMember.DeclaringType))
                {
                    if (member.LocalMember.Name == "Value")
                    {
                        customizer.Column(member.PreviousPath.LocalMember.Name);
                    }
                    else if (member.LocalMember.Name != "Owner")
                    {
                        customizer.Column(member.PreviousPath.LocalMember.Name + member.LocalMember.Name);
                    }
                }
            };


            mapper.Component <RestrictedVisibility <string> >(x => {
                x.Property(c => c.Value);
                x.Property(c => c.Visibility);
                x.Parent(c => c.Owner);
            });

            mapper.Component <RestrictedVisibility <bool> >(x => {
                x.Property(c => c.Value);
                x.Property(c => c.Visibility);
                x.Parent(c => c.Owner);
            });

            // The following probably works, but not if we stop "Owner" from being a persistent property
            // using mapping.IsPersistentProperty, and if we don't do that we get a Too Many Properties exception.
            // There's an old thread on nhusers about how there's no documentation in this area...
            //mapper.BeforeMapComponent += (inspector, member, customizer) => {
            //    if (member.LocalMember.Name == "Owner") {
            //        customizer.Parent(member.LocalMember);
            //    }
            //};

            AddConventionOverrides(mapper);

            HbmMapping mapping = mapper.CompileMappingFor(
                typeof(Entity).Assembly.GetExportedTypes().Where(IsEntity));

            configuration.AddDeserializedMapping(mapping, "MyStoreMappings");
        }