Пример #1
0
        public void DiscriminatorValuePatternsAppliersPacksComposition()
        {
            // In this example I will compose various packs to customize the mapping.
            // In this case I concern on the two packs about Table-per-class-hierarchy discriminator value pattern
            // Note: both DiscriminatorValueAsClassNamePack and DiscriminatorValueAsEnumValuePack does contain DiscriminatorColumnNameApplier but with the Merge
            // it will be applied just once

            var orm = new ObjectRelationalMapper();

            // The follow line show how compose patterns-appliers-packs and patterns-appliers
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new BidirectionalOneToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))                         // <== NOTE: it can be used together with DiscriminatorValueAsEnumValuePack
                .Merge(new DiscriminatorValueAsEnumValuePack <Item, ItemTypes>(orm))       // <== NOTE: it can be used together with DiscriminatorValueAsClassNamePack
                .Merge(new CoolTablesAndColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entities
            orm.TablePerClassHierarchy <Item>();
            orm.TablePerClassHierarchy <Something>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Item).Assembly.GetTypes().Where(t => t.Namespace == typeof(Item).Namespace));

            Console.Write(mapping.AsString());
        }
Пример #2
0
        public void HighLowCustomization()
        {
            // In this example you can see how configure the HighLowPoidPattern with a per hierarchy 'where' clause

            var orm = new ObjectRelationalMapper();

            orm.Patterns.PoidStrategies.Add(new HighLowPoidPattern(poidProperty => new
            {
                table  = "NextHighVaues",
                column = "NextHigh",
                max_lo = 100,
                where  = string.Format("Entity = '{0}'", poidProperty.ReflectedType.GetRootEntity(orm).Name)
            }));

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm);

            orm.TablePerClassHierarchy <Product>();
            orm.TablePerClass <Customer>();

            var entities = new[] { typeof(Product), typeof(Customer) };
            var mapping  = mapper.CompileMappingFor(entities);

            Console.Write(mapping.AsString());

            // with the follow line you can add the script, to populate the HighLow table, directly to the NH's configuration
            // the SchemaExport will do the work.
            //nhConfiguration.AddAuxiliaryDatabaseObject(CreateHighLowScript(orm, entities));
        }
Пример #3
0
        public void ComposingPatternsAppliersPacks()
        {
            // Thanks to Lorenzo Vegetti to provide the domain of this example.
            // This example refers to a little-domain, interesting from the point of view of mapping with ConfORM.
            // Here you can see how apply general convetion, how and when compose patterns-appliers-packs and patterns-appliers,
            // how ConfORM can apply different mapping depending on the type of enum (see the difference on CostOptions) and so on...
            // You don't have to organize the mapping all in one class, as in this example, and you don't have to use the IModuleMapping...
            // You can organize the mapping as you feel more confortable for your application; in some case a class is enough, in other cases would
            // be better the separation per module/concern, you are not closed in "mapping per class" box.

            var orm = new ObjectRelationalMapper();

            // With the follow line I'm adding the pattern for the POID strategy ("native" instead the default "High-Low")
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());

            // composition of patterns-appliers-packs and patterns-appliers for Lorenzo's domain
            // Note: for bidirectional-one-to-many association Lorenzo is not interested in the default cascade behavior,
            // implemented in the BidirectionalOneToManyRelationPack, because he is using a sort of soft-delete in his base class VersionModelBase.
            // He can implements a custom pack of patterns-appliers to manage the situation when classes does not inherits from VersionModelBase by the way
            // he don't want the cascade atall, so the BidirectionalOneToManyInverseApplier will be enough
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                    .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                    .Merge(new BidirectionalOneToManyInverseApplier(orm))
                    .Merge(new EnumAsStringPack())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Setting the version property using the base class
            orm.VersionProperty<VersionModelBase>(v => v.Version);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy<Cost>();
            orm.TablePerClass<EditionQuotation>();
            orm.TablePerClass<ProductQuotation>();
            orm.TablePerClass<Quotation>();

            AppliesGeneralConventions(mapper);

            // EditionQuotation.PrintCost don't use lazy-loading
            mapper.Customize<EditionQuotation>(map => map.ManyToOne(eq => eq.PrintCost, m2o => m2o.Lazy(LazyRelation.NoLazy)));

            // Customizes some others DDL's stuff outside conventions
            CustomizeColumns(mapper);

            // Note : I have to create mappings for the whole domain
            HbmMapping mapping =
                mapper.CompileMappingFor(
                    typeof (GenericModelBase<>).Assembly.GetTypes().Where(t => t.Namespace == typeof (GenericModelBase<>).Namespace));
            Console.Write(mapping.AsString());
        }
Пример #4
0
 private static HbmMapping GetMapping()
 {
     var orm = new ObjectRelationalMapper();
     var mapper = new Mapper(orm,
     new CoolPatternsAppliersHolder(orm));
     orm.TablePerClassHierarchy<Product>();
     orm.TablePerClass<ActorRole>();
     orm.Patterns.PoidStrategies.Add(
     new GuidOptimizedPoidPattern());
     orm.VersionProperty<Entity>(x => x.Version);
     orm.NaturalId<Product>(p => p.Name);
     orm.Cascade<Movie, ActorRole>(
     Cascade.All | Cascade.DeleteOrphans);
     mapper.AddPropertyPattern(mi =>
     mi.GetPropertyOrFieldType() == typeof(Decimal) &&
     mi.Name.Contains("Price"),
     pm => pm.Type(NHibernateUtil.Currency));
     mapper.AddPropertyPattern(mi =>
     orm.IsRootEntity(mi.DeclaringType) &&
     !"Description".Equals(mi.Name),
     pm => pm.NotNullable(true));
     mapper.Subclass<Movie>(cm =>
     cm.List(movie => movie.Actors,
     colm => colm.Index(
     lim => lim.Column("ActorIndex")), m => { }));
     var domainClasses = typeof(Entity).Assembly.GetTypes()
     .Where(t => typeof(Entity).IsAssignableFrom(t));
     return mapper.CompileMappingFor(domainClasses);
 }
        public void ComposingPatternsAppliersPacks()
        {
            // In this example I will compose various packs to customize the mapping.
            // The result is the same of ConfOrm.UsageExamples.Packs.SimpleDemo but this time using patterns-appliers-packs composition (instead its short-cut CoolPatternsAppliersHolder).
            // To play with patterns-appliers-packs-composition you need a more complex domain; adding and removing packs you can see
            // how change your mapping.

            // What is a patterns-appliers-pack:
            // It is an implementation of IPatternsAppliersHolder focused in a specific concern;
            // for example CoolTablesAndColumnsNamingPack is focused to set columns and table names.

            var orm = new ObjectRelationalMapper();

            // The follow line show how compose patterns-appliers-packs and patterns-appliers
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new BidirectionalOneToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolTablesAndColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy<Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));
            Console.Write(mapping.AsString());
        }
 public void RegisteringComponentAndEntityThrow()
 {
     var mapper = new ObjectRelationalMapper();
     mapper.Component<AComponent>();
     ActionAssert.Throws(() => mapper.TablePerClass<AComponent>()).Should().Be.InstanceOf<MappingException>();
     ActionAssert.Throws(() => mapper.TablePerConcreteClass<AComponent>()).Should().Be.InstanceOf<MappingException>();
     ActionAssert.Throws(() => mapper.TablePerClassHierarchy<AComponent>()).Should().Be.InstanceOf<MappingException>();
 }
Пример #7
0
        public void RegisteringComponentAndEntityThrow()
        {
            var mapper = new ObjectRelationalMapper();

            mapper.Component <AComponent>();
            Executing.This(() => mapper.TablePerClass <AComponent>()).Should().Throw().And.Exception.Should().Be.InstanceOf <MappingException>();
            Executing.This(() => mapper.TablePerConcreteClass <AComponent>()).Should().Throw().And.Exception.Should().Be.InstanceOf <MappingException>();
            Executing.This(() => mapper.TablePerClassHierarchy <AComponent>()).Should().Throw().And.Exception.Should().Be.InstanceOf <MappingException>();
        }
        public void WhenExplicitExcludedThenNotTablePerClassHierarchy()
        {
            // To prevent inconsistence
            var orm = new ObjectRelationalMapper();
            orm.TablePerClassHierarchy<ToExcludeImplEntity>();
            orm.Exclude<ToExcludeImplEntity>();

            orm.IsTablePerClassHierarchy(typeof(ToExcludeImplEntity)).Should().Be.False();
        }
Пример #9
0
        private void ConfOrmMapping(ObjectRelationalMapper orm, Mapper mapper)
        {
            orm.TablePerClassHierarchy <Product>();

            orm.ManyToMany <Customer, Product>();
            orm.Cascade <Movie, ActorRole>(Cascade.All);

            orm.NaturalId <Customer>(c => c.Name);
        }
        public void WhenExplicitExcludedThenNotTablePerClassHierarchy()
        {
            // To prevent inconsistence
            var orm = new ObjectRelationalMapper();

            orm.TablePerClassHierarchy <ToExcludeImplEntity>();
            orm.Exclude <ToExcludeImplEntity>();

            orm.IsTablePerClassHierarchy(typeof(ToExcludeImplEntity)).Should().Be.False();
        }
        public void DomainDefinition(ObjectRelationalMapper orm)
        {
            orm.TablePerClass<Animal>();
            orm.TablePerClass<User>();
            orm.TablePerClass<StateProvince>();
            orm.TablePerClassHierarchy<Zoo>();

            orm.ManyToMany<Human, Human>();
            orm.OneToOne<User, Human>();
        }
Пример #12
0
        public void ExclusionDemo()
        {
            var orm = new ObjectRelationalMapper();

            // In this case I want exclude any implementation of Movement<TDetail> and MovementDetail<TMovement>.
            // Where the type if not generic or you have to jump a specific concrete-type you can use the method Exclude<TClass> (see ConfOrmTests.ObjectRelationalMapperTests.HierarchyClassExclusionTest)
            orm.Exclude(typeof(Movement<>));
            orm.Exclude(typeof(MovementDetail<>));

            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm)); // <== CoolPatternsAppliersHolder is not important... only nice to have

            // The strategy to represent classes is not important
            orm.TablePerClassHierarchy<Movement>();
            orm.TablePerClassHierarchy<MovementDetail>();

            // Show the mapping to the console
            var mapping = mapper.CompileMappingFor(typeof(Movement).Assembly.GetTypes().Where(t => t.Namespace == typeof(Movement).Namespace));
            Console.Write(mapping.AsString());
        }
        public void DomainDefinition(ObjectRelationalMapper orm)
        {
            orm.TablePerClass <Animal>();
            orm.TablePerClass <User>();
            orm.TablePerClass <StateProvince>();
            orm.TablePerClassHierarchy <Zoo>();

            orm.ManyToMany <Human, Human>();
            orm.OneToOne <User, Human>();
        }
Пример #14
0
        public void ExclusionDemo()
        {
            var orm = new ObjectRelationalMapper();

            // In this case I want exclude any implementation of Movement<TDetail> and MovementDetail<TMovement>.
            // Where the type if not generic or you have to jump a specific concrete-type you can use the method Exclude<TClass> (see ConfOrmTests.ObjectRelationalMapperTests.HierarchyClassExclusionTest)
            orm.Exclude(typeof(Movement <>));
            orm.Exclude(typeof(MovementDetail <>));

            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));             // <== CoolPatternsAppliersHolder is not important... only nice to have

            // The strategy to represent classes is not important
            orm.TablePerClassHierarchy <Movement>();
            orm.TablePerClassHierarchy <MovementDetail>();

            // Show the mapping to the console
            var mapping = mapper.CompileMappingFor(typeof(Movement).Assembly.GetTypes().Where(t => t.Namespace == typeof(Movement).Namespace));

            Console.Write(mapping.AsString());
        }
        public void IntegrationWithObjectRelationalMapper()
        {
            var orm = new ObjectRelationalMapper();
            orm.TablePerClassHierarchy<EntitySimple>();
            HbmMapping mapping = GetMapping(orm);
            VerifyEntitySimpleMapping(mapping);

            HbmClass rc = mapping.RootClasses.Single();
            rc.Id.generator.Should("The ORM should assign a default generator").Not.Be.Null();

            VerifyHinheritedMapping(mapping);
        }
Пример #16
0
        public void RegisterTablePerClassHierarchy()
        {
            var entitiesTypes = new[] { typeof(MyClass1), typeof(MyClass2) };
            var orm           = new ObjectRelationalMapper();

            orm.TablePerClassHierarchy(entitiesTypes);
            orm.IsTablePerClassHierarchy(typeof(MyClass1)).Should().Be(true);
            orm.IsTablePerClassHierarchy(typeof(MyClass2)).Should().Be(true);

            orm.IsTablePerConcreteClass(typeof(MyClass1)).Should().Be(false);
            orm.IsTablePerClass(typeof(MyClass2)).Should().Be(false);
        }
        public void WithoutDiscriminatorValueAsClassNamePack()
        {
            // In this example show the result of the mapping but WITHOUT merge the CoolPatternsAppliersHolder with DiscriminatorValueAsClassNamePack
            // this mean that will be used the default behavior and column names defined in NHibernate

            var orm = new ObjectRelationalMapper();
            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));

            orm.TablePerClassHierarchy<Animal>();

            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));
            Console.Write(mapping.AsString());
        }
        public void WithoutDiscriminatorValueAsClassNamePack()
        {
            // In this example show the result of the mapping but WITHOUT merge the CoolPatternsAppliersHolder with DiscriminatorValueAsClassNamePack
            // this mean that will be used the default behavior and column names defined in NHibernate

            var orm    = new ObjectRelationalMapper();
            var mapper = new Mapper(orm, new CoolPatternsAppliersHolder(orm));

            orm.TablePerClassHierarchy <Animal>();

            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));

            Console.Write(mapping.AsString());
        }
        public void IntegrationWithObjectRelationalMapper()
        {
            var orm = new ObjectRelationalMapper();

            orm.TablePerClassHierarchy <EntitySimple>();
            HbmMapping mapping = GetMapping(orm);

            VerifyEntitySimpleMapping(mapping);

            HbmClass rc = mapping.RootClasses.Single();

            rc.Id.generator.Should("The ORM should assign a default generator").Not.Be.Null();

            VerifyHinheritedMapping(mapping);
        }
Пример #20
0
        public void UsageOfRequiredInTablePerClassHierarchy()
        {
            var orm = new ObjectRelationalMapper();

            orm.Patterns.Poids.Add(new PoidByAttributePattern());
            orm.TablePerClassHierarchy <CourseList>();

            var mapper = new Mapper(orm);

            mapper.PatternsAppliers.Merge(new RequiredPropertyPatternApplier(orm));
            mapper.PatternsAppliers.Merge(new StringLengthApplier());

            var mapping = mapper.CompileMappingFor(new[] { typeof(CourseList), typeof(SpecialCourseList) });

            Console.Write(mapping.AsString());
        }
        public HbmMapping GetMapping()
        {
            #region Initialize ConfORM

            var orm = new ObjectRelationalMapper();
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new BidirectionalOneToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolTablesNamingPack(orm))
                .Merge(new CoolColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new UseNoLazyForNoProxablePack())                         // <== Lazy false when the class is not proxable
                .Merge(new ConfOrm.Shop.CoolNaming.UnidirectionalOneToManyMultipleCollectionsKeyColumnApplier(orm))
                .Merge(new UseCurrencyForDecimalApplier())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            orm.Patterns.PoidStrategies.Add(new HighLowPoidPattern(new { max_lo = 100 }));

            var mapper = new Mapper(orm, patternsAppliers);

            var domainEntities = typeof(Entity)
                                 .Assembly.GetTypes()
                                 .Where(t => (typeof(AbstractEntity <int>).IsAssignableFrom(t) || typeof(AbstractEntity <Guid>).IsAssignableFrom(t)) &&
                                        !t.IsGenericType)
                                 .ToList();

            IEnumerable <Type> tablePerClassEntities = typeof(Entity)
                                                       .Assembly.GetTypes().Where(t => IsRootEntity(t) &&
                                                                                  !tablePerClassHierarchy.Contains(t) &&
                                                                                  !tablePerConcreteClass.Contains(t)).ToList();

            // Mappings
            orm.TablePerClass(tablePerClassEntities);
            orm.TablePerClassHierarchy(tablePerClassHierarchy);
            orm.TablePerConcreteClass(tablePerConcreteClass);

            #endregion

            ConfOrmMapping(orm, mapper);

            return(mapper.CompileMappingFor(domainEntities));
        }
Пример #22
0
        private Mapper GetMapper()
        {
            #region Initialize ConfORM
            //var inflector = new EnglishInflector();

            var orm = new ObjectRelationalMapper();
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new SafePoidPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new BidirectionalOneToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolTablesNamingPack(orm))
                //.Merge(new PluralizedTablesPack(orm, inflector))
                .Merge(new CoolColumnsNamingPack(orm))
                //.UnionWith(new ConfOrm.Shop.InflectorNaming.CollectionOfElementsColumnApplier(orm, inflector))
                .Merge(new PolymorphismPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new UseNoLazyForNoProxablePack())                         // <== Lazy false when the class is not proxable
                .Merge(new ConfOrm.Shop.CoolNaming.UnidirectionalOneToManyMultipleCollectionsKeyColumnApplier(orm))
                .Merge(new UseCurrencyForDecimalApplier())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            orm.Patterns.PoidStrategies.Add(new HighLowPoidPattern(new { max_lo = 100 }));

            var mapper = new Mapper(orm, patternsAppliers);

            IEnumerable <Type> tablePerClassEntities = typeof(Entity)
                                                       .Assembly.GetTypes().Where(t => IsRootEntity(t) &&
                                                                                  !tablePerClassHierarchy.Contains(t) &&
                                                                                  !tablePerConcreteClass.Contains(t)).ToList();

            // Mappings
            orm.AddToDomain(typeof(Entity).Assembly.GetTypes());
            orm.TablePerClass(tablePerClassEntities);
            orm.TablePerClassHierarchy(tablePerClassHierarchy);
            orm.TablePerConcreteClass(tablePerConcreteClass);

            #endregion

            ConfOrmMapping(orm, mapper);
            return(mapper);
        }
Пример #23
0
        public void CallBeforeEventBeforeFirstPatternApplier()
        {
            var callSequence = new List <string>();
            var orm          = new ObjectRelationalMapper();

            orm.TablePerClassHierarchy <MyClass>();

            var patternsAppliersHolder = new EmptyPatternsAppliersHolder();

            patternsAppliersHolder.Subclass.Add(t => true, (t, cam) => callSequence.Add("pa"));

            var mapper = new Mapper(orm, patternsAppliersHolder);

            mapper.BeforeMapSubclass += (di, t, cam) => callSequence.Add("beforeevent");
            mapper.CompileMappingFor(new[] { typeof(MyClass), typeof(Inherited) });

            callSequence.Should().Have.SameSequenceAs("beforeevent", "pa");
        }
Пример #24
0
        public void CallAfterEventAfterLastCustomizer()
        {
            var callSequence = new List <string>();
            var orm          = new ObjectRelationalMapper();

            orm.TablePerClassHierarchy <MyClass>();

            var patternsAppliersHolder = new EmptyPatternsAppliersHolder();
            var mapper = new Mapper(orm, patternsAppliersHolder);

            mapper.AfterMapSubclass += (di, t, cam) => callSequence.Add("afterevent");

            mapper.Subclass <Inherited>(ca => callSequence.Add("c1"));
            mapper.Subclass <Inherited>(ca => callSequence.Add("c2"));
            mapper.CompileMappingFor(new[] { typeof(MyClass), typeof(Inherited) });

            callSequence.Should().Have.SameSequenceAs("c1", "c2", "afterevent");
        }
        public HbmMapping GenerateMappings()
        {
            var domainEntities = GetDomainEntities().ToArray();

            var relationalMapper = new ObjectRelationalMapper();
            relationalMapper.TablePerClassHierarchy(domainEntities);
            relationalMapper.Patterns.PoidStrategies.Add(new HighLowPoidPattern());

            var patternsAppliers = new CoolPatternsAppliersHolder(relationalMapper);
            patternsAppliers.Merge(new ClassPluralizedTableApplier(new EnglishInflector()));
            patternsAppliers.Merge(new UseNoLazyForNoProxablePack());
            var mapper = new Mapper(relationalMapper, patternsAppliers);

            var mapping = mapper.CompileMappingFor(domainEntities);
            Debug.WriteLine(Serialize(mapping));

            return mapping;
        }
Пример #26
0
        private static ObjectRelationalMapper GetORM()
        {
            var orm = new ObjectRelationalMapper();
              orm.TablePerClassHierarchy<Product>();
              orm.TablePerClass<ActorRole>();

              orm.NaturalId<Product>(p => p.Name);

              orm.Cascade<Movie, ActorRole>(
            Cascade.All | Cascade.DeleteOrphans);

              orm.Patterns.PoidStrategies
            .Add(new GuidOptimizedPoidPattern());

              orm.Patterns.Versions
            .Add(new MyVersionPattern());

              return orm;
        }
Пример #27
0
        public HbmMapping GenerateMappigs()
        {
            var orm = new ObjectRelationalMapper();

            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());

            //// map .NET4 ISet<T> as a NHibernate's set
            orm.Patterns.Sets.Add(new UseSetWhenGenericCollectionPattern());
            var englishInflector = new EnglishInflector();
            IPatternsAppliersHolder patternsAppliers = (new SafePropertyAccessorPack())
                                                       .Merge(new ClassPluralizedTableApplier(englishInflector))
                                                       .Merge(new DiscriminatorValueAsEnumValuePack <ChildA, Types>(orm))
                                                       .Merge(new DiscriminatorValueAsEnumValuePack <ChildB, Types>(orm))
                                                       .Merge(new CoolPatternsAppliersHolder(orm));

            IEnumerable <Type> allPersistEntities = GetDomainEntities();

            IEnumerable <Type> roots = allPersistEntities.Where(t => t.IsAbstract && t.InheritedFromBaseEntity());

            IEnumerable <Type> hierarchyEntities = allPersistEntities.Where(t => typeof(IHierarchyEntity).IsAssignableFrom(t));

            IEnumerable <Type> separateEntities = allPersistEntities.Except(roots).Except(hierarchyEntities);

            orm.TablePerConcreteClass(separateEntities);

            var hierarchyRoots = hierarchyEntities.Where(t => t.IsAbstract && t.InheritedFromBaseEntity());

            orm.TablePerClassHierarchy(hierarchyRoots);

            orm.Cascade <ChildA, Container>(CascadeOn.Persist | CascadeOn.Merge);
            orm.Cascade <Container, ChildA>(CascadeOn.Persist);

            orm.Cascade <ChildB, Container>(CascadeOn.Persist | CascadeOn.Merge);
            orm.Cascade <Container, ChildB>(CascadeOn.Persist);

            var mapper = new Mapper(orm, patternsAppliers);

            HbmMapping mapping = mapper.CompileMappingFor(allPersistEntities);

            File.WriteAllText(@"c:\Test\mappings.xml", Serialize(mapping)); // сохраняем маппинги в файл.
            return(mapping);
        }
Пример #28
0
        public HbmMapping GenerateMappings()
        {
            var domainEntities = GetDomainEntities().ToArray();

            var relationalMapper = new ObjectRelationalMapper();

            relationalMapper.TablePerClassHierarchy(domainEntities);
            relationalMapper.Patterns.PoidStrategies.Add(new HighLowPoidPattern());

            var patternsAppliers = new CoolPatternsAppliersHolder(relationalMapper);

            patternsAppliers.Merge(new ClassPluralizedTableApplier(new EnglishInflector()));
            patternsAppliers.Merge(new UseNoLazyForNoProxablePack());
            var mapper = new Mapper(relationalMapper, patternsAppliers);

            var mapping = mapper.CompileMappingFor(domainEntities);

            Debug.WriteLine(Serialize(mapping));

            return(mapping);
        }
        public void AddAppliersPackToGivenCoolPatternsAppliersHolder()
        {
            // In this example I will add the DiscriminatorValueAsClassNamePack to customize the mapping con discriminator column name and values
            // for table-per-class-hierarchy mapping

            var orm = new ObjectRelationalMapper();

            // Merge of CoolPatternsAppliersHolder with DiscriminatorValueAsClassNamePack
            // IMPORTANT: In this case the Merge extension will return a new instance of IPatternsAppliersHolder with the result of the merge.
            var patternsAppliers = (new CoolPatternsAppliersHolder(orm)).Merge(new DiscriminatorValueAsClassNamePack(orm));

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy<Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));
            Console.Write(mapping.AsString());
        }
        public void AddAppliersPackToGivenCoolPatternsAppliersHolder()
        {
            // In this example I will add the DiscriminatorValueAsClassNamePack to customize the mapping con discriminator column name and values
            // for table-per-class-hierarchy mapping

            var orm = new ObjectRelationalMapper();

            // Merge of CoolPatternsAppliersHolder with DiscriminatorValueAsClassNamePack
            // IMPORTANT: In this case the Merge extension will return a new instance of IPatternsAppliersHolder with the result of the merge.
            var patternsAppliers = (new CoolPatternsAppliersHolder(orm)).Merge(new DiscriminatorValueAsClassNamePack(orm));

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy <Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));

            Console.Write(mapping.AsString());
        }
        public void ComposingPatternsAppliersPacks()
        {
            // In this example I will compose various packs to customize the mapping.
            // The result is the same of ConfOrm.UsageExamples.Packs.SimpleDemo but this time using patterns-appliers-packs composition (instead its short-cut CoolPatternsAppliersHolder).
            // To play with patterns-appliers-packs-composition you need a more complex domain; adding and removing packs you can see
            // how change your mapping.

            // What is a patterns-appliers-pack:
            // It is an implementation of IPatternsAppliersHolder focused in a specific concern;
            // for example CoolTablesAndColumnsNamingPack is focused to set columns and table names.

            var orm = new ObjectRelationalMapper();

            // The follow line show how compose patterns-appliers-packs and patterns-appliers
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new BidirectionalOneToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolTablesAndColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy <Animal>();

            // Note : I have to create mappings for the whole domain
            var mapping = mapper.CompileMappingFor(typeof(Animal).Assembly.GetTypes().Where(t => t.Namespace == typeof(Animal).Namespace));

            Console.Write(mapping.AsString());
        }
Пример #32
0
        public void ComposingPatternsAppliersPacks()
        {
            // Thanks to Lorenzo Vegetti to provide the domain of this example.
            // This example refers to a little-domain, interesting from the point of view of mapping with ConfORM.
            // Here you can see how apply general convetion, how and when compose patterns-appliers-packs and patterns-appliers,
            // how ConfORM can apply different mapping depending on the type of enum (see the difference on CostOptions) and so on...
            // You don't have to organize the mapping all in one class, as in this example, and you don't have to use the IModuleMapping...
            // You can organize the mapping as you feel more confortable for your application; in some case a class is enough, in other cases would
            // be better the separation per module/concern, you are not closed in "mapping per class" box.

            var orm = new ObjectRelationalMapper();

            // With the follow line I'm adding the pattern for the POID strategy ("native" instead the default "High-Low")
            orm.Patterns.PoidStrategies.Add(new NativePoidPattern());

            // composition of patterns-appliers-packs and patterns-appliers for Lorenzo's domain
            // Note: for bidirectional-one-to-many association Lorenzo is not interested in the default cascade behavior,
            // implemented in the BidirectionalOneToManyRelationPack, because he is using a sort of soft-delete in his base class VersionModelBase.
            // He can implements a custom pack of patterns-appliers to manage the situation when classes does not inherits from VersionModelBase by the way
            // he don't want the cascade atall, so the BidirectionalOneToManyInverseApplier will be enough
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                .Merge(new OneToOneRelationPack(orm))
                .Merge(new BidirectionalManyToManyRelationPack(orm))
                .Merge(new DiscriminatorValueAsClassNamePack(orm))
                .Merge(new CoolColumnsNamingPack(orm))
                .Merge(new TablePerClassPack())
                .Merge(new PluralizedTablesPack(orm, new EnglishInflector()))
                .Merge(new ListIndexAsPropertyPosColumnNameApplier())
                .Merge(new BidirectionalOneToManyInverseApplier(orm))
                .Merge(new EnumAsStringPack())
                .Merge(new DatePropertyByNameApplier())
                .Merge(new MsSQL2008DateTimeApplier());

            // Instancing the Mapper using the result of Merge
            var mapper = new Mapper(orm, patternsAppliers);

            // Setting the version property using the base class
            orm.VersionProperty <VersionModelBase>(v => v.Version);

            // Note: I'm declaring the strategy only for the base entity
            orm.TablePerClassHierarchy <Cost>();
            orm.TablePerClass <EditionQuotation>();
            orm.TablePerClass <ProductQuotation>();
            orm.TablePerClass <Quotation>();

            AppliesGeneralConventions(mapper);

            // EditionQuotation.PrintCost don't use lazy-loading
            mapper.Customize <EditionQuotation>(map => map.ManyToOne(eq => eq.PrintCost, m2o => m2o.Lazy(LazyRelation.NoLazy)));

            // Customizes some others DDL's stuff outside conventions
            CustomizeColumns(mapper);

            // Note : I have to create mappings for the whole domain
            HbmMapping mapping =
                mapper.CompileMappingFor(
                    typeof(GenericModelBase <>).Assembly.GetTypes().Where(t => t.Namespace == typeof(GenericModelBase <>).Namespace));

            Console.Write(mapping.AsString());
        }
Пример #33
0
        private Mapper GetMapper()
        {
            #region Initialize ConfORM
            var inflector = new SpanishInflector();

            var orm = new ObjectRelationalMapper();

            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new SafePoidPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new BidirectionalOneToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new PluralizedTablesPack(orm, inflector))
                    .Merge(new CoolColumnsNamingPack(orm))
                    .UnionWith(new ConfOrm.Shop.InflectorNaming.CollectionOfElementsColumnApplier(orm, inflector))
                    .Merge(new PolymorphismPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new UseNoLazyForNoProxablePack()) // <== Lazy false when the class is not proxable
                    .Merge(new UnidirectionalOneToManyMultipleCollectionsKeyColumnApplier(orm))
                    .Merge(new UseCurrencyForDecimalApplier());

            // orm.Patterns.PoidStrategies.Add(new HighLowPoidPattern(new {max_lo = 100}));

            var mapper = new Mapper(orm, patternsAppliers);

            IEnumerable<Type> tablePerClassEntities =
                typeof(Entity).Assembly.GetTypes().Where(
                    t => IsRootEntity(t) && !_tablePerClassHierarchy.Contains(t) && !_tablePerConcreteClass.Contains(t)).ToList();

            // Mappings
            orm.TablePerClass(tablePerClassEntities);
            orm.TablePerClassHierarchy(_tablePerClassHierarchy);
            orm.TablePerConcreteClass(_tablePerConcreteClass);
            #endregion

            ConfOrmMapping(orm, mapper);

            return mapper;
        }
        public HbmMapping GetMapping()
        {
            #region Initialize ConfORM

            var orm = new ObjectRelationalMapper();
            IPatternsAppliersHolder patternsAppliers =
                (new SafePropertyAccessorPack())
                    .Merge(new OneToOneRelationPack(orm))
                    .Merge(new BidirectionalManyToManyRelationPack(orm))
                    .Merge(new BidirectionalOneToManyRelationPack(orm))
                    .Merge(new DiscriminatorValueAsClassNamePack(orm))
                    .Merge(new CoolTablesNamingPack(orm))
                    .Merge(new CoolColumnsNamingPack(orm))
                    .Merge(new TablePerClassPack())
                    .Merge(new UseNoLazyForNoProxablePack()) // <== Lazy false when the class is not proxable
                    .Merge(new ConfOrm.Shop.CoolNaming.UnidirectionalOneToManyMultipleCollectionsKeyColumnApplier(orm))
                    .Merge(new UseCurrencyForDecimalApplier())
                    .Merge(new DatePropertyByNameApplier())
                    .Merge(new MsSQL2008DateTimeApplier());

            orm.Patterns.PoidStrategies.Add(new HighLowPoidPattern(new {max_lo = 100}));

            var mapper = new Mapper(orm, patternsAppliers);

            var domainEntities = typeof (Entity)
                .Assembly.GetTypes()
                .Where(t => (typeof (AbstractEntity<int>).IsAssignableFrom(t) || typeof (AbstractEntity<Guid>).IsAssignableFrom(t))
                    && !t.IsGenericType)
                .ToList();

            IEnumerable<Type> tablePerClassEntities = typeof (Entity)
                .Assembly.GetTypes().Where(t => IsRootEntity(t)
                                                && !tablePerClassHierarchy.Contains(t)
                                                && !tablePerConcreteClass.Contains(t)).ToList();

            // Mappings
            orm.TablePerClass(tablePerClassEntities);
            orm.TablePerClassHierarchy(tablePerClassHierarchy);
            orm.TablePerConcreteClass(tablePerConcreteClass);

            #endregion

            ConfOrmMapping(orm, mapper);

            return mapper.CompileMappingFor(domainEntities);
        }