예제 #1
0
        private static HbmMapping GetMappings(Type baseEntityToIgnore, Assembly mappingsAssembly, string mappingsNamespace,
                                              bool mapAllEnumsToStrings, Action <ModelMapper> autoMappingOverride, bool showLogs, string outputXmlMappingsFile)
        {
            //Using the built-in auto-mapper
            var mapper = new ConventionModelMapper();

            DefineBaseClass(mapper, new[] { baseEntityToIgnore });
            var allEntities = mappingsAssembly.GetTypes().Where(t => t.Namespace == mappingsNamespace).ToList();

            mapper.AddAllManyToManyRelations(allEntities);
            mapper.ApplyNamingConventions();
            if (mapAllEnumsToStrings)
            {
                mapper.MapAllEnumsToStrings();
            }
            if (autoMappingOverride != null)
            {
                autoMappingOverride(mapper);
            }

            var mapping = mapper.CompileMappingFor(allEntities);

            showOutputXmlMappings(mapping, showLogs, outputXmlMappingsFile);
            return(mapping);
        }
예제 #2
0
파일: Program.cs 프로젝트: xxfcz/NHCookbook
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            var nhConfig       = new Configuration().Configure();
            var sessionFactory = nhConfig.BuildSessionFactory();

            Console.WriteLine("NHibernate configured by App.config!");

            //var foo = new NeedLog();
            //foo.DoSomething();

            var mapper = new ConventionModelMapper();

            nhConfig.AddMapping(mapper.CompileMappingFor(new[] { typeof(TestClass) }));
            var schemaExport = new SchemaExport(nhConfig);

            //schemaExport.Create(false, true);
            //Console.WriteLine("已创建表!");

            schemaExport.SetOutputFile("db.sql").Execute(false, false, false);
            Console.WriteLine("生成了SQL文件:{0}", Path.GetFullPath("db.sql"));

            Console.ReadKey();
        }
        /// <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(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>();

            return(mapper.CompileMappingFor(allEntities));
        }
예제 #4
0
        public void Test_AbstractIntermediateSubclasses()
        {
            var mapper = new ConventionModelMapper();

            mapper.IsTablePerClass((type, declared) => false);
            mapper.IsTablePerClassHierarchy((type, declared) => true);
            var mappings = mapper.CompileMappingFor(new[] { typeof(Animal), typeof(Mammal), typeof(Dog) });

            Assert.AreEqual(1, mappings.RootClasses.Length, "Mapping should only have Animal as root class");
            Assert.AreEqual(2, mappings.SubClasses.Length, "Subclasses not mapped as expected");
            var animalMapping = mappings.RootClasses.SingleOrDefault(s => s.Name == nameof(Animal));

            Assert.IsNotNull(animalMapping, "Unable to find mapping for animal class");
            Assert.AreEqual(nameof(Animal.Id), animalMapping.Id.name, "Identifier not mapped as expected");
            CollectionAssert.AreEquivalent(new [] { nameof(Animal.Description), nameof(Animal.Sequence) }, animalMapping.Properties.Select(p => p.Name));
            var mammalMapping = mappings.SubClasses.SingleOrDefault(s => s.Name == nameof(Mammal));

            Assert.IsNotNull(mammalMapping, "Unable to find mapping for Mammal class");
            Assert.AreEqual(nameof(Animal), mammalMapping.extends, "Mammal mapping does not extend Animal as expected");
            CollectionAssert.AreEquivalent(new[] { nameof(Mammal.Pregnant), nameof(Mammal.BirthDate) }, mammalMapping.Properties.Select(p => p.Name));
            var dogMapping = mappings.SubClasses.SingleOrDefault(s => s.Name == nameof(Dog));

            Assert.IsNotNull(dogMapping, "Unable to find mapping for Dog class");
            Assert.AreEqual(nameof(Mammal), dogMapping.extends, "Dog mapping does not extend Mammal as expected");
            CollectionAssert.IsEmpty(dogMapping.Properties);
        }
예제 #5
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;
            }
        }
예제 #6
0
        public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration)
        {
            Type baseEntityType = typeof(Entity);

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

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

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

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

            AddConventionOverrides(mapper);

            HbmMapping mapping = mapper.CompileMappingFor(typeof(Customer).Assembly.GetExportedTypes().Where(t => IsEntity(t)));

            configuration.AddDeserializedMapping(mapping, "MyStoreMappings");
        }
예제 #7
0
        private static HbmMapping GetMappings(IEnumerable <Assembly> mappingsAssemblies)
        {
            //Using the built-in auto-mapper
            var mapper = new ConventionModelMapper();

            DefineBaseClass(mapper);
            var allEntities = new List <Type>();

            foreach (var mappingsAssembly in mappingsAssemblies)
            {
                allEntities.AddRange(mappingsAssembly.GetTypes().Where(
                                         t => BaseEntityToIgnore.IsAssignableFrom(t) &&
                                         t != BaseEntityToIgnore &&
                                         !t.IsInterface
                                         ).ToList());
            }
            mapper.AddAllManyToManyRelations(allEntities);
            mapper.ApplyNamingConventions();
            if (MapAllEnumsToStrings)
            {
                mapper.MapAllEnumsToStrings();
            }
            if (AutoMappingOverride != null)
            {
                AutoMappingOverride(mapper);
            }
            OverrideByClassMapping(mapper, mappingsAssemblies);

            var mapping = mapper.CompileMappingFor(allEntities);

            //ShowOutputXmlMappings(mapping);
            return(mapping);
        }
예제 #8
0
        public void Test_Longchain3_ConventionMappingMappings_PerClass()
        {
            // Mapped -> Unmapped -> Mapped -> Root
            var mapper = new ConventionModelMapper();

            mapper.IsTablePerClass((type, declared) => true);
            mapper.IsTablePerClassHierarchy((type, declared) => false);
            var mappings = mapper.CompileMappingFor(new[] { typeof(Longchain3.MappedRoot), typeof(Longchain3.MappedExtension), typeof(Longchain3.TopLevel) });

            Assert.AreEqual(1, mappings.RootClasses.Length, "Mapping should only have MappedRoot as root class");
            Assert.AreEqual(2, mappings.JoinedSubclasses.Length, "Subclasses not mapped as expected");
            var rootMapping = mappings.RootClasses.SingleOrDefault(s => s.Name == nameof(Longchain3.MappedRoot));

            Assert.IsNotNull(rootMapping, "Unable to find mapping for MappedRoot class");
            Assert.AreEqual(nameof(Longchain3.MappedRoot.Id), rootMapping.Id.name, "Identifier not mapped as expected");
            CollectionAssert.AreEquivalent(new[] { nameof(Longchain3.MappedRoot.BaseField) }, rootMapping.Properties.Select(p => p.Name));
            var mappedExtensionMapping = mappings.JoinedSubclasses.SingleOrDefault(s => s.Name == nameof(Longchain3.MappedExtension));

            Assert.IsNotNull(mappedExtensionMapping, "Unable to find mapping for MappedExtension class");
            Assert.AreEqual(nameof(Longchain3.MappedRoot), mappedExtensionMapping.extends, "MappedExtension extension not as expected");
            CollectionAssert.AreEquivalent(new[] { nameof(Longchain3.FirstUnmappedExtension.FirstUnmappedExtensionField), nameof(Longchain3.MappedExtension.MappedExtensionField) }, mappedExtensionMapping.Properties.Select(p => p.Name));
            var topLevelMapping = mappings.JoinedSubclasses.SingleOrDefault(s => s.Name == nameof(Longchain3.TopLevel));

            Assert.IsNotNull(topLevelMapping, "Unable to find mapping for TopLevel class");
            Assert.AreEqual(nameof(Longchain3.MappedExtension), topLevelMapping.extends, "TopLevel extension not as expected");
            CollectionAssert.AreEquivalent(new[] { nameof(Longchain3.SecondUnmappedExtension.SecondUnmappedExtensionField), nameof(Longchain3.TopLevel.TopLevelExtensionField) }, topLevelMapping.Properties.Select(p => p.Name));
        }
예제 #9
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);
        }
예제 #10
0
        protected override HbmMapping GetMappings()
        {
            var mapper = new ConventionModelMapper();

            mapper.BeforeMapClass += (t, mi, map) => map.Id(idm => idm.Generator(Generators.Native));
            return(mapper.CompileMappingFor(new[] { typeof(Something) }));
        }
        public override Configuration Map(Configuration cfg)
        {
            ConventionModelMapper mapper = new ConventionModelMapper();

            mapper.IsEntity((x, y) => this.IsEntity(x, y, this.EntitiesAssemblyName));
            mapper.IsRootEntity((x, y) => this.IsRootEntity(x, y, this.EntitiesAssemblyName));
            mapper.IsOneToMany((x, y) => this.IsOneToMany(x, y));
            mapper.IsManyToOne((x, y) => this.IsManyToOne(x, y));
            mapper.IsManyToMany((x, y) => this.IsManyToMany(x, y));
            mapper.IsBag((x, y) => this.IsBag(x, y));
            mapper.IsSet((x, y) => this.IsSet(x, y));
            mapper.IsProperty((x, y) => this.IsProperty(x, y));
            mapper.IsPersistentProperty((x, y) => this.IsPersistentProperty(x, y));
            mapper.BeforeMapClass      += this.BeforeMapClass;
            mapper.BeforeMapProperty   += this.BeforeMapProperty;
            mapper.BeforeMapSet        += this.BeforeMapSet;
            mapper.BeforeMapOneToMany  += this.BeforeMapOneToMany;
            mapper.BeforeMapManyToOne  += this.BeforeMapManyToOne;
            mapper.BeforeMapManyToMany += BeforeMapManyToMany;

            HbmMapping mappings = mapper.CompileMappingFor(Assembly.Load(this.EntitiesAssemblyName).GetExportedTypes());

            cfg.AddMapping(mappings);

            return(cfg);
        }
예제 #12
0
파일: Fixture.cs 프로젝트: jrauber/GH1429
        protected override HbmMapping GetMappings()
        {
            var mapper = new ConventionModelMapper();

            mapper.BeforeMapClass += (mi, t, x) => x.Id(map => map.Generator(Generators.Guid));
            return(mapper.CompileMappingFor(new[] { typeof(MyClass) }));
        }
예제 #13
0
        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
                    }
            }
        }
        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, Does.Not.Contain("field"));
        }
예제 #15
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);
        }
        public void WhenPropertyWithDifferentBackFieldMatch()
        {
            var mapper     = new ConventionModelMapper();
            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            var hbmClass    = hbmMapping.RootClasses[0];
            var hbmProperty = hbmClass.Properties.Single(x => x.Name == "WithDifferentBackField");

            hbmProperty.Access.Should().Contain("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");

            Assert.That(hbmProperty.Access, Is.Null.Or.Empty);
        }
        public void WhenSetOnlyPropertyNoMatch()
        {
            var mapper     = new ConventionModelMapper();
            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            var hbmClass    = hbmMapping.RootClasses[0];
            var hbmProperty = hbmClass.Properties.Single(x => x.Name == "SetOnlyProperty");

            Assert.That(hbmProperty.Access, Is.Null.Or.Not.Contain("field"));
        }
        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");

            Assert.That(hbmProperty.Access, Is.Null.Or.Empty);
        }
예제 #20
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];

            Assert.That(hbmClass.Id.access, Is.EqualTo("nosetter.camelcase-underscore"));
        }
        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");

            Assert.That(hbmProperty.Access, Is.EqualTo("field"));
        }
        public void WhenPropertyWithoutFieldNoMatch()
        {
            var mapper = new ConventionModelMapper();

            mapper.Class <MyClass>(mc => mc.Property(x => x.PropertyWithoutField));

            var hbmMapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            var hbmClass    = hbmMapping.RootClasses[0];
            var hbmProperty = hbmClass.Properties.Single(x => x.Name == "PropertyWithoutField");

            hbmProperty.Access.Should().Not.Contain("field");
        }
예제 #23
0
        public static Configuration Initialize()
        {
            INHibernateConfigurationCache cache = new NHibernateConfigurationFileCache();

            var mappingAssemblies = new[] {
                typeof(Customer).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 = "MyStoreConnectionString";
                    db.Dialect <MsSql2008Dialect>();
                })
                .AddAssembly(typeof(Customer).Assembly)
                .CurrentSessionContext <LazySessionContext>();

                var mapper = new ConventionModelMapper();

                mapper.AddMappings(new List <Type>()
                {
                    typeof(NhIdentityUserMapping),
                    typeof(NhIdentityUserRoleMapping),
                    typeof(NhNhIdentityUserLoginMapping),
                    typeof(NhIdentityUserClaimMapping)
                });
                var mapping = mapper.CompileMappingFor(new List <Type>()
                {
                    typeof(NhIdentityUser),
                    typeof(NhIdentityUserRole),
                    typeof(NhIdentityUserLogin),
                    typeof(NhIdentityUserClaim)
                });
                var lastCompiledXml = mapping.AsString();
                configuration.AddDeserializedMapping(mapping, "IdentityMappings");

                mapper.WithConventions(configuration);

                cache.SaveConfiguration(CONFIG_CACHE_KEY, configuration);
            }

            return(configuration);
        }
예제 #24
0
        public HbmMapping GetHbmMapping()
        {
            var mapper = new ConventionModelMapper();

            var mappings = GetMappings();

            foreach (var mapping in mappings)
            {
                mapping.ApplyMapping(mapper);
            }

            var entityTypes = GetAutomappedEntityTypes();

            return(mapper.CompileMappingFor(entityTypes));
        }
예제 #25
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;

            Assert.That(hbmId, Is.Not.Null);
            Assert.That(hbmId.generator, Is.Not.Null);
            Assert.That(hbmId.generator.@class, Is.EqualTo("guid"));
            Assert.That(hbmId.type1, Is.EqualTo("Guid"));
        }
예제 #26
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;

            Assert.That(hbmId, Is.Not.Null);
            Assert.That(hbmId.generator, Is.Not.Null);
            Assert.That(hbmId.generator.@class, Is.EqualTo("native"));
            Assert.That(hbmId.type1, Is.EqualTo(Generators.Native.DefaultReturnType.GetNhTypeName()));
        }
예제 #27
0
        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);
        }
        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);
        }
예제 #29
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");
        }
예제 #30
0
        private HbmMapping getMappings()
        {
            //Using the built-in auto-mapper
            var mapper      = new ConventionModelMapper();
            var allEntities = MappingsAssembly.GetTypes().Where(t => t.Namespace == MappingsNamespace).ToList();

            mapper.AddAllManyToManyRelations(allEntities);
            mapper.ApplyNamingConventions();
            if (AutoMappingOverride != null)
            {
                AutoMappingOverride(mapper);
            }
            var mapping = mapper.CompileMappingFor(allEntities);

            showOutputXmlMappings(mapping);
            return(mapping);
        }
        private Configuration ConfigureNHibernate()
        {
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
                    {
                        db.Dialect<SQLiteDialect>();
                        db.Driver<SQLite20Driver>();
                        db.SchemaAction = SchemaAutoAction.Recreate;
                        db.ConnectionString = "Data Source=:memory:;Version=3;New=True;";
                    }).SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var mapper = new ConventionModelMapper();

            // filter entities
            var baseEntityType = typeof(AbstractEntity);
            mapper.IsEntity(
                (t, declared) => baseEntityType.IsAssignableFrom(t) && baseEntityType != t && !t.IsInterface);
            mapper.IsRootEntity((t, declared) => baseEntityType == t.BaseType);

            // override base properties
            mapper.Class<AbstractEntity>(map => map.Id(x => x.Id, m => m.Generator(Generators.GuidComb)));

            mapper.BeforeMapProperty += (modelinspector, member, propertycustomizer) =>
                                            {
                                                if (member.LocalMember.Name == "Name")
                                                {
                                                    propertycustomizer.Unique(true);
                                                }
                                            };

            // compile
            var mapping =
                mapper.CompileMappingFor(
                    typeof(Person).Assembly.GetExportedTypes().Where(
                        type => typeof(AbstractEntity).IsAssignableFrom(type)));

            // use mappings
            config.AddMapping(mapping);

            return config;
        }