Exemple #1
0
        public void WhenMapPropertiesInTheBaseJumpedClassUsingMemberNameThenMapInInherited()
        {
            // ignoring MyClass and using Inherited, as root-class, I will try to map all properties using the base class.
            // NH have to recognize the case and map those properties in the inherited.
            var inspector = new SimpleModelInspector();

            inspector.IsEntity((type, declared) => type == typeof(Inherited));
            inspector.IsRootEntity((type, declared) => type == typeof(Inherited));
            var mapper = new ModelMapper(inspector);

            mapper.Class <MyClass>(mc =>
            {
                mc.Id(x => x.Id);
                mc.Property("Simple", map => map.Access(Accessor.Field));
                mc.Property("ComplexType", map => map.Access(Accessor.Field));
                mc.Bag <string>("Bag", y => y.Access(Accessor.Field));
                mc.IdBag <MyCompo>("IdBag", y => y.Access(Accessor.Field));
                mc.List <string>("List", y => y.Access(Accessor.Field));
                mc.Set <string>("Set", y => y.Access(Accessor.Field));
                mc.Map <int, string>("Map", y => y.Access(Accessor.Field));
                mc.OneToOne <Related>("OneToOne", y => y.Access(Accessor.Field));
                mc.ManyToOne <Related>("ManyToOne", y => y.Access(Accessor.Field));
                mc.Any <object>("Any", typeof(int), y => y.Access(Accessor.Field));
                mc.Component("DynamicCompo", new { A = 2 }, y => y.Access(Accessor.Field));
                mc.Component <MyCompo>("Compo", y =>
                {
                    y.Access(Accessor.Field);
                    y.Property(c => c.Something);
                });
            });
            mapper.Class <Inherited>(mc => { });

            HbmMapping mappings = mapper.CompileMappingForAllExplicitlyAddedEntities();
            HbmClass   hbmClass = mappings.RootClasses[0];

            mappings.JoinedSubclasses.Should().Be.Empty();
            hbmClass.Properties.Select(p => p.Name).Should().Have.SameValuesAs("Simple", "ComplexType", "Bag", "IdBag", "List", "Set", "Map", "Compo", "OneToOne", "ManyToOne", "Any",
                                                                               "DynamicCompo");
            hbmClass.Properties.Select(p => p.Access).All(x => x.Satisfy(access => access.Contains("field.")));
        }
Exemple #2
0
        public static string GetShortClassName(this System.Type type, HbmMapping mapDoc)
        {
            if (type == null)
            {
                return(null);
            }
            if (mapDoc == null)
            {
                return(type.AssemblyQualifiedName);
            }
            string typeAssembly         = type.Assembly.GetName().Name;
            string typeAssemblyFullName = type.Assembly.FullName;
            string typeNameSpace        = type.Namespace;
            string assembly             = null;

            if (typeAssembly != mapDoc.assembly && typeAssemblyFullName != mapDoc.assembly)
            {
                assembly = typeAssembly;
            }
            string @namespace = null;

            if (typeNameSpace != mapDoc.@namespace)
            {
                @namespace = typeNameSpace;
            }
            if (!string.IsNullOrEmpty(assembly) && !string.IsNullOrEmpty(@namespace))
            {
                return(type.AssemblyQualifiedName);
            }
            if (!string.IsNullOrEmpty(assembly) && string.IsNullOrEmpty(@namespace))
            {
                return(string.Concat(GetTypeNameForMapping(type), ", ", assembly));
            }
            if (string.IsNullOrEmpty(assembly) && !string.IsNullOrEmpty(@namespace))
            {
                return(type.FullName);
            }

            return(GetTypeNameForMapping(type));
        }
        public void WhenPropertyUsedAsComposedIdAndPropertiesThenNotUsedAsSimpleProperties()
        {
            var mapper = new ModelMapper();

            mapper.Class <MyClass>(map =>
            {
                map.ComposedId(cm =>
                {
                    cm.Property(x => x.Code);
                    cm.ManyToOne(x => x.Relation);
                });
                map.Property(x => x.Code);
                map.ManyToOne(x => x.Relation);
            }
                                   );
            HbmMapping     hbmMapping    = mapper.CompileMappingFor(new[] { typeof(MyClass) });
            HbmClass       hbmClass      = hbmMapping.RootClasses[0];
            HbmCompositeId hbmCompositId = hbmClass.CompositeId;

            hbmCompositId.Items.Should().Have.Count.EqualTo(2);
            hbmClass.Properties.Should().Be.Empty();
        }
        protected static HbmMapping GetMappings()
        {
            ModelMapper mapper = new ModelMapper();

            mapper.AddMapping <DjelatnikOsobaMap>();
            mapper.AddMapping <KategorijaMap>();
            mapper.AddMapping <KupacOsobaMap>();
            mapper.AddMapping <OsobaMap>();
            mapper.AddMapping <ProizvodMap>();
            mapper.AddMapping <RacunMap>();
            mapper.AddMapping <StavkaMap>();
            mapper.AddMapping <StavkaKupovinaMap>();
            mapper.AddMapping <StavkaPosudbaMap>();
            mapper.AddMapping <StavkaServisMap>();
            mapper.AddMapping <VrstaPlacanjaMap>();
            mapper.AddMapping <ZanimanjeMap>();

            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Djelatnik), typeof(Kategorija), typeof(Kupac), typeof(Osoba), typeof(Proizvod),
                                                                  typeof(Racun), typeof(Stavka), typeof(StavkaKupovina), typeof(StavkaPosudba), typeof(StavkaServis), typeof(VrstaPlacanja), typeof(Zanimanje) });

            return(mapping);
        }
Exemple #5
0
        public void WhenPropertyUsedAsComposedIdAndPropertiesThenNotUsedAsSimpleProperties()
        {
            var mapper = new ModelMapper();

            mapper.Class <MyClass>(map =>
            {
                map.ComposedId(cm =>
                {
                    cm.Property(x => x.Code);
                    cm.ManyToOne(x => x.Relation);
                });
                map.Property(x => x.Code);
                map.ManyToOne(x => x.Relation);
            }
                                   );
            HbmMapping     hbmMapping    = mapper.CompileMappingFor(new[] { typeof(MyClass) });
            HbmClass       hbmClass      = hbmMapping.RootClasses[0];
            HbmCompositeId hbmCompositId = hbmClass.CompositeId;

            Assert.That(hbmCompositId.Items, Has.Length.EqualTo(2));
            Assert.That(hbmClass.Properties, Is.Empty);
        }
Exemple #6
0
        public void ExclusionDemo()
        {
            var orm = new ObjectRelationalMapper();

            orm.Patterns.Poids.Add(new MyPoidProperty());             // <== recognize the property representing the POID

            IPatternsAppliersHolder patternsAppliers =
                (new CoolPatternsAppliersHolder(orm))
                .UnionWith(new MyTablesAndColumnsNamingPack());                         // <=== Note the usage of UnionWith instead Merge

            var mapper = new Mapper(orm, patternsAppliers);

            // The strategy to represent classes is not important
            orm.TablePerClass <PorBoxEO>();
            orm.TablePerClass <PorEO>();

            // Show the mapping to the console
            HbmMapping mapping =
                mapper.CompileMappingFor(new[] { typeof(PorEO), typeof(PorBoxEO) });

            Console.Write(mapping.AsString());
        }
Exemple #7
0
        public void WhenCustomizeNestedComponetPerPropertyThenEachPropertyInDifferentWays()
        {
            Mock <IDomainInspector> orm = GetMockedDomainInspector();

            var domainInspector = orm.Object;
            var mapper          = new Mapper(domainInspector);

            mapper.Class <MyClass>(cm =>
            {
                cm.Component(myclass => myclass.ComponentLevel00, compo00 => compo00.Component(c => c.ComponentLevel1, compo00_1 => compo00_1.Lazy(true)));
                cm.Component(myclass => myclass.ComponentLevel01, compo01 => compo01.Component(c => c.ComponentLevel1, compo00_1 => compo00_1.Lazy(false)));
            });

            HbmMapping mapping   = mapper.CompileMappingFor(new[] { typeof(MyClass) });
            HbmClass   rc        = mapping.RootClasses.First(r => r.Name.Contains("MyClass"));
            var        relation0 = ((HbmComponent)rc.Properties.First(p => p.Name == "ComponentLevel00")).Properties.First(p => p.Name == "ComponentLevel1");

            relation0.IsLazyProperty.Should().Be.True();
            var relation1 = ((HbmComponent)rc.Properties.First(p => p.Name == "ComponentLevel01")).Properties.First(p => p.Name == "ComponentLevel1");

            relation1.IsLazyProperty.Should().Be.False();
        }
        public void WhenMapClassElementsThenMapParent()
        {
            var mapper = new ModelMapper();

            mapper.Class <Person>(cm =>
            {
                cm.Id(x => x.Id);
                cm.Bag(x => x.Addresses, cp => { }, cr => cr.Component(ce =>
                {
                    ce.Parent(x => x.Owner);
                    ce.Property(x => x.Street);
                    ce.Component(x => x.Number, y =>
                    {
                        y.Parent(x => x.OwnerAddress, map => { });
                        y.Property(x => x.Block);
                    });
                }));
            });
            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            VerifyMapping(mapping, true, "Street", "Number");
        }
Exemple #9
0
        private void VerifyMapping(HbmMapping mapping)
        {
            var dialect       = new MsSql2008Dialect();
            var configuration = new Configuration();
            var mappings      = configuration.CreateMappings(dialect);

            mappings.DefaultAssembly  = "NHibernate.Test";
            mappings.DefaultNamespace = "NHibernate.Test.NHSpecificTest.NH1007";

            var rootBinder = new MappingRootBinder(mappings, dialect);

            rootBinder.Bind(mapping);

            var employer    = rootBinder.Mappings.GetClass("NHibernate.Test.NHSpecificTest.NH1007.Employer1");
            var simpleValue = employer.Identifier as SimpleValue;

            if (simpleValue != null)
            {
                Assert.That(simpleValue.IdentifierGeneratorStrategy, Is.EqualTo("guid"));
                Assert.That(simpleValue.IdentifierGeneratorProperties, Is.Empty);
            }
        }
Exemple #10
0
        public static ISession OpenSession()
        {
            var cfg = new Configuration()
                      .DataBaseIntegration(db =>
            {
                string connectionString = @"Data Source=|DataDirectory|\db\data.db";
                //string connectionString = string.Format("Data Source={0}", @"|DataDirectory|\db\data.db");
                db.ConnectionString = connectionString;
                //db.ConnectionString = @"Data Source = App_Data\data.db;";
                db.Dialect <SQLiteDialect>();
            });
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);
            new SchemaUpdate(cfg).Execute(true, true);
            ISessionFactory sessionFactory = cfg.BuildSessionFactory();

            return(sessionFactory.OpenSession());
        }
Exemple #11
0
        private static string Serialize(HbmMapping hbmElement)
        {
            string result;
            var    setting = new XmlWriterSettings {
                Indent = true
            };
            var serializer = new XmlSerializer(typeof(HbmMapping));

            using (var memStream = new MemoryStream(2048))
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memStream, setting))
                {
                    serializer.Serialize(xmlWriter, hbmElement);
                }
                memStream.Position = 0;
                using (var sr = new StreamReader(memStream))
                {
                    result = sr.ReadToEnd();
                }
            }
            return(result);
        }
Exemple #12
0
        public MySqlEventSource(MySqlConnectionString connectionString, EventDispatcher publisher)
        {
            var cfg = new Configuration()
                      .DataBaseIntegration(db =>
            {
                db.ConnectionString = (String)connectionString;
                db.Dialect <MySQLDialect>();
            });

            /* Add the mapping we defined: */
            var mapper = new ModelMapper();

            mapper.AddMapping(typeof(RecordedEventMap));
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            this.factory = cfg.BuildSessionFactory();

            this._publisher = publisher;
            this._aggregateIdToStreamName = (t, g) => string.Format("{0}-{1}", char.ToLower(t.Name[0]) + t.Name.Substring(1), g);
        }
Exemple #13
0
        internal ISessionFactory CreateSessionFactory()
        {
            var cfg = new global::NHibernate.Cfg.Configuration().DataBaseIntegration(x =>
            {
                x.ConnectionString = connectionString;
                x.Driver <OracleManagedDataClientDriver>();
                x.Dialect <Oracle10gDialect>();
                x.LogSqlInConsole = true;
            });

            var mapper = new ModelMapper();

            mapper.AddMapping <TimeoutEntityMap>();
            mapper.AddMapping <StagedTimeoutEntityMap>();

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);
            cfg.SetProperty("hbm2ddl.auto", "update"); // creates the schema, destroying previous data

            return(cfg.BuildSessionFactory());
        }
Exemple #14
0
        public void CallCustomizerOfEachProperty()
        {
            Mock <IDomainInspector> orm = GetMockedDomainInspector();
            var  mapper = new Mapper(orm.Object);
            bool simplePropertyCalled = false;
            bool bagCalled            = false;
            bool listCalled           = false;
            bool setCalled            = false;
            bool mapCalled            = false;
            bool manyToOneCalled      = false;
            bool oneToOneCalled       = false;
            bool anyCalled            = false;
            bool componentCalled      = false;

            mapper.Customize <MyClass>(x =>
            {
                x.Property(mc => mc.SimpleProperty, pm => simplePropertyCalled = true);
                x.Collection(mc => mc.Bag, pm => bagCalled            = true);
                x.Collection(mc => mc.List, pm => listCalled          = true);
                x.Collection(mc => mc.Set, pm => setCalled            = true);
                x.Collection(mc => mc.Map, pm => mapCalled            = true);
                x.ManyToOne(mc => mc.ManyToOne, pm => manyToOneCalled = true);
                x.OneToOne(mc => mc.OneToOne, pm => oneToOneCalled    = true);
                x.Any(mc => mc.Any, pm => anyCalled = true);
                x.Component(mc => mc.Component, pm => componentCalled = true);
            });

            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(MyClass) });

            simplePropertyCalled.Should().Be.True();
            bagCalled.Should().Be.True();
            listCalled.Should().Be.True();
            setCalled.Should().Be.True();
            mapCalled.Should().Be.True();
            manyToOneCalled.Should().Be.True();
            oneToOneCalled.Should().Be.True();
            anyCalled.Should().Be.True();
            componentCalled.Should().Be.True();
        }
Exemple #15
0
        public void SetupContext()
        {
            var cfg = new Configuration()
                      .DataBaseIntegration(x =>
            {
                x.Dialect <SQLiteDialect>();
                x.ConnectionString = string.Format(@"Data Source={0};Version=3;New=True;", Path.GetTempFileName());
            });

            var mapper = new ModelMapper();

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

            cfg.AddMapping(faultMappings);

            new SchemaExport(cfg).Create(false, true);

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

            storage = new SubscriptionStorage(subscriptionStorageSessionProvider);
        }
Exemple #16
0
        public ISessionFactory GetSessionFactory()
        {
            Configuration cfg = new Configuration()
                                .DataBaseIntegration(db =>
                                                     //{
                                                     //    DataAccess da = CUS.EX.DAL.EXConnect.GetDataAccess();

                                                     //});


            {
                //db.ConnectionString = ConfigSettings.Current.DatabaseConnectionInfo.ConnectionString;
                db.ConnectionString = "Data Source=TUL-DRBREASHEAR\\MSSQLSERVER01;Initial Catalog=DEV_700;Persist Security Info=True;User ID=sa;Password=Dave22sa!";
                //db.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["EXConnectionString"].ConnectionString;
                //db.ConnectionString = "Data Source=JenzDB01;Initial Catalog=TmsEPrd;Persist Security Info=True;User ID=sa;Password=SASQLmidlandcollege!";
                //db.ConnectionString = "Data Source=JenzDB01;Initial Catalog=TmsEUpgradeTest;Persist Security Info=True;User ID=sa;Password=SASQLmidlandcollege!";
                db.Dialect <MsSql2005Dialect>();
                db.IsolationLevel = IsolationLevel.ReadUncommitted;
                db.Driver <SqlClientDriver>();
            });

            cfg.Proxy(pr =>
            {
                pr.ProxyFactoryFactory <NHibernate.Bytecode.DefaultProxyFactoryFactory>();
            });

            cfg.AddAssembly("FacCred");

            var mapper = new ModelMapper();

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

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            return(cfg.BuildSessionFactory());
        }
Exemple #17
0
        public AnyMapper(MemberInfo member, Type foreignIdType, HbmAny any, HbmMapping mapDoc)
        {
            this.member        = member;
            this.foreignIdType = foreignIdType;
            this.any           = any;
            this.mapDoc        = mapDoc;
            if (member == null)
            {
                this.any.access = "none";
            }
            if (member == null)
            {
                entityPropertyMapper = new NoMemberPropertyMapper();
            }
            else
            {
                entityPropertyMapper = new AccessorPropertyMapper(member.DeclaringType, member.Name, x => any.access = x);
            }
            if (foreignIdType == null)
            {
                throw new ArgumentNullException("foreignIdType");
            }
            if (any == null)
            {
                throw new ArgumentNullException("any");
            }

            this.any.idtype = this.foreignIdType.GetNhTypeName();
            var idHbmColumn  = new HbmColumn();
            var idColumnName = member == null ? DefaultIdColumnNameWhenNoProperty : member.Name + "Id";

            idColumnMapper = new ColumnMapper(idHbmColumn, idColumnName);
            var classHbmColumn  = new HbmColumn();
            var classColumnName = member == null ? DefaultMetaColumnNameWhenNoProperty : member.Name + "Class";

            classColumnMapper = new ColumnMapper(classHbmColumn, classColumnName);
            any.column        = new[] { idHbmColumn, classHbmColumn };
        }
        public void WhenMapClassWithWrongElementsThenAutodiscoverParent()
        {
            // In this case the user will use wrong mapping-elements as ManyToOne and Component (he should realize that it end in an infinite loop)
            var mapper = new ModelMapper();

            mapper.Class <Person>(cm =>
            {
                cm.Id(x => x.Id);
                cm.Bag(x => x.Addresses, cp => { }, cr => cr.Component(ce =>
                {
                    ce.ManyToOne(x => x.Owner);
                    ce.Property(x => x.Street);
                    ce.Component(x => x.Number, y =>
                    {
                        y.Component(x => x.OwnerAddress, map => { });
                        y.Property(x => x.Block);
                    });
                }));
            });
            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            VerifyMapping(mapping, false, "Street", "Number", "Owner");
        }
Exemple #19
0
        public static ISessionFactory GetService(string connectionString)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes);
            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            var configuration = new Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect <PostgreSQLDialect>();
                c.ConnectionString   = connectionString;
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.SchemaAction       = SchemaAutoAction.Validate;
                c.LogFormattedSql    = true;
                c.LogSqlInConsole    = true;
            });
            configuration.AddMapping(domainMapping);
            var sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }
        /// <summary>
        /// Configures the storage with the user supplied persistence configuration
        /// DB schema is updated if requested by the user
        /// </summary>
        /// <param name="config"></param>
        /// <param name="nhibernateProperties"></param>
        /// <param name="autoUpdateSchema"></param>
        /// <returns></returns>
        public static Configure DBSubcriptionStorage(this Configure config,
                                                     Configuration configuration,
                                                     bool autoUpdateSchema)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping faultMappings = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(faultMappings);

            if (autoUpdateSchema)
            {
                new SchemaUpdate(configuration).Execute(false, true);
            }

            var sessionSource = new SubscriptionStorageSessionProvider(configuration.BuildSessionFactory());

            config.Configurer.RegisterSingleton <ISubscriptionStorageSessionProvider>(sessionSource);
            config.Configurer.ConfigureComponent <SubscriptionStorage>(DependencyLifecycle.InstancePerCall);

            return(config);
        }
        ISessionFactory CreateSessionFactory()
        {
            var cfg = new Configuration().DataBaseIntegration(x =>
            {
                x.ConnectionString = connectionString;
                x.LogSqlInConsole  = true;
            });

            databaseDialect.ConfigureDriverAndDialect(cfg);

            var mapper = new ModelMapper();

            mapper.AddMapping <TimeoutEntityMap>();
            mapper.AddMapping <StagedTimeoutEntityMap>();
            mapper.AddMapping <MigrationsEntityMap>();

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);
            cfg.SetProperty("hbm2ddl.auto", "update");

            return(cfg.BuildSessionFactory());
        }
        public NHibernateRepository()
        {
            if (NHibernateRepository.sessionFactory == null)
            {
                var mapper = new ModelMapper();
                mapper.AddMappings(this.GetType().Assembly.ExportedTypes.Where(x => x.Namespace == "moura.painel.NHibernate.Maps").ToArray());
                HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                var configuration = new Configuration();
                configuration.DataBaseIntegration(c =>
                {
                    c.Dialect <MsSql2008Dialect>();
                    c.ConnectionString   = this.GetConnectonString();
                    c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                    c.SchemaAction       = SchemaAutoAction.Validate;
                    c.LogFormattedSql    = true;
                    c.LogSqlInConsole    = true;
                });
                configuration.AddMapping(domainMapping);

                NHibernateRepository.sessionFactory = configuration.BuildSessionFactory();
            }
        }
Exemple #23
0
        public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString)
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(ProductoMap).Assembly.ExportedTypes);
            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            var configuration = new Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect <NHibernate.Dialect.MySQLDialect>();
                c.ConnectionString = connectionString;
            });
            configuration.AddMapping(domainMapping);

            var sessionFactory = configuration.BuildSessionFactory();

            services.AddSingleton(sessionFactory);
            services.AddScoped(factory => sessionFactory.OpenSession());

            return(services);
        }
Exemple #24
0
        private static Configuration buildConfig(ReadModelConnectionString connectionString)
        {
            var cfg = new Configuration().DataBaseIntegration(
                db =>
            {
                db.ConnectionString = (String)connectionString;
                db.Dialect <MySQLDialect>();
            });

            /* Add the mapping we defined: */
            var mapper = new ModelMapper();

            mapper.AddMappings(
                Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where <Type>(g => g.FullName.EndsWith("Map") || g.IsSubclassOf(typeof(ClassMapping))));

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            return(cfg);
        }
Exemple #25
0
        /// <summary>
        /// Gets the Configuration for the SessionFactory using the configuration for a MySql database and the connection string.
        /// </summary>
        /// <returns>The configuration.</returns>
        private Configuration getConfiguration()
        {
            if (this.config == null)
            {
                this.config = new Configuration();
                this.config.DataBaseIntegration((db) =>
                {
                    db.Dialect <MySQL55Dialect>();
                    db.Driver <MySqlDataDriver>();
                    db.ConnectionString = this.configService.GetConnectionString("db");
                });
            }

            var mapper = new ModelMapper();

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

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            this.config.AddMapping(mapping);

            return(this.config);
        }
    public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString)
    {
        // set serilog as default logger for nhibernate
        NHibernateLogger.SetLoggersFactory(new NHibernate.Logging.Serilog.SerilogLoggerFactory());

        // standard config for nhibernate(could have been done in appsettings.json
        var mapper = new ModelMapper();

        mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes);
        HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

        var configuration = new Configuration();

        configuration.DataBaseIntegration(c =>
        {
            c.Dialect <MsSql2012Dialect>();
            c.ConnectionString   = connectionString;
            c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            //c.SchemaAction = SchemaAutoAction.Validate;
            c.LogFormattedSql = true;
            c.LogSqlInConsole = true;
        });
        configuration.AddMapping(domainMapping);

        var sessionFactory = configuration.BuildSessionFactory();

        // recreate db each time
        SchemaExport se = new SchemaExport(configuration);

        se.Drop(true, true);
        se.Create(true, true);

        services.AddSingleton(sessionFactory);
        services.AddScoped(factory => sessionFactory.OpenSession());

        return(services);
    }
Exemple #27
0
        public static HbmMapping Generate()
        {
            //Conventions
            var mapper     = new ConventionModelMapper();
            var baseEntity = typeof(EntityBase);

            mapper.BeforeMapProperty += (ispector, member, customizer) => customizer.Length(40);

            mapper.BeforeMapManyToOne +=
                (insp, prop, map) => map.Column(prop.LocalMember.GetPropertyOrFieldType().Name + "Id");

            mapper.BeforeMapManyToOne +=
                (insp, prop, map) => map.Cascade(Cascade.Persist);

            mapper.BeforeMapBag +=
                (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));

            mapper.BeforeMapSet +=
                (insp, prop, map) => map.Key(km => km.Column(prop.GetContainerEntity(insp).Name + "Id"));

            mapper.IsEntity((t, d) => baseEntity.IsAssignableFrom(t) && baseEntity != t);

            mapper.IsRootEntity((t, d) => t.BaseType == baseEntity);

            mapper.IsSet(IsSetFieldType);

            Customize(mapper);

            HbmMapping mappings = mapper.CompileMappingFor(new[]
            {
                typeof(Customization), typeof(Order),
                typeof(Payment),
                typeof(OrderItem), typeof(Product)
            });

            return(mappings);
        }
Exemple #28
0
        static void Main(string[] args)
        {
            var cfg = new Configuration().DataBaseIntegration(db =>
            {
                db.ConnectionString = "Data Source=.;Initial Catalog=NP;Integrated Security=True";
                db.Dialect <MsSql2012Dialect>();
            });

            var mapper = new ModelMapper();

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

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            cfg.AddMapping(mapping);

            new SchemaExport(cfg).Execute(x => { }, false, false, TextWriter.Null);

            using (ISessionFactory factory = cfg.BuildSessionFactory())
            {
                using (ISession session = factory.OpenSession())
                {
                    using (ITransaction tx = session.BeginTransaction())
                    {
                        var product = new Product()
                        {
                            Id = Guid.NewGuid(), Name = "aaa", Price = 13.90
                        };
//                        var orderItem1 = new OrderItem() { Id = Guid.NewGuid(), ProductNumber = 1, Product = product };
//                        var orderItem2 = new OrderItem() { Id = Guid.NewGuid(), ProductNumber = 3, Product = product };
//                        var order = new Order() { Id = Guid.NewGuid(), Code = "111", Items = new List<OrderItem>() { orderItem1, orderItem2 } };
                        session.Save(product);
                        tx.Commit();
                    }
                }
            }
        }
        public virtual void MapTypes(List <Type> allTypes, NHibernate.Cfg.Configuration cfg, Func <string, string> formatter)
        {
            var m = new HbmMapping();

            m.Items = allTypes.Select(t =>
            {
                var sc                = new HbmSubclass();
                sc.name               = GetName(t);
                sc.extends            = GetName(t.BaseType);
                sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name;
                sc.lazy               = false;
                sc.lazySpecified      = true;

                var propertyMappings = GetPersistables(t)
                                       .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter))
                                       .ToList();
                if (propertyMappings.Count > 0)
                {
                    if (sc.Items == null)
                    {
                        sc.Items = propertyMappings.ToArray();
                    }
                    else
                    {
                        sc.Items = sc.Items.Union(propertyMappings).ToArray();
                    }
                }

                return(sc);
            }).ToArray();
            if (Debugger.IsAttached)
            {
                var dbg = m.AsString();
            }
            cfg.AddDeserializedMapping(m, "N2");
        }
        public void WhenMapClasByClassThenAutodiscoverParent()
        {
            var mapper = new ModelMapper();

            mapper.Component <Address>(cm =>
            {
                cm.ManyToOne(x => x.Owner);
                cm.Property(x => x.Street);
                cm.Component(x => x.Number, y => { });
            });
            mapper.Component <Number>(cm =>
            {
                cm.Component(x => x.OwnerAddress, map => { });
                cm.Property(x => x.Block);
            });
            mapper.Class <Person>(cm =>
            {
                cm.Id(x => x.Id);
                cm.Bag(x => x.Addresses, cp => { }, cr => { });
            });
            HbmMapping mapping = mapper.CompileMappingFor(new[] { typeof(Person) });

            VerifyMapping(mapping, false, "Street", "Number", "Owner");
        }