/// <summary> /// Builds the session factory with the given properties. Database is updated if updateSchema is set /// </summary> public ISessionFactory Build(Configuration nhibernateConfiguration) { var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct(); foreach (var assembly in scannedAssemblies) { nhibernateConfiguration.AddAssembly(assembly); } var modelMapper = new SagaModelMapper(typesToScan.Except(nhibernateConfiguration.ClassMappings.Select(x => x.MappedClass))); nhibernateConfiguration.AddMapping(modelMapper.Compile()); try { return nhibernateConfiguration.BuildSessionFactory(); } catch (Exception e) { if (e.InnerException != null) throw new ConfigurationErrorsException(e.InnerException.Message, e); throw; } }
public void SetUp() { connectionString = String.Format(@"Data Source={0};New=True;", Path.GetTempFileName()); var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary <string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, connectionString } }); var modelMapper = new SagaModelMapper(new[] { typeof(T) }); configuration.AddMapping(modelMapper.Compile()); SessionFactory = configuration.BuildSessionFactory(); new SchemaUpdate(configuration).Execute(false, true); session = SessionFactory.OpenSession(); SagaPersister = new SagaPersister(new FakeSessionProvider(SessionFactory, session)); new Installer().Install(WindowsIdentity.GetCurrent().Name, null); }
/// <summary> /// Builds the session factory with the given properties. Database is updated if updateSchema is set /// </summary> public ISessionFactory Build(Configuration nhibernateConfiguration) { var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct(); foreach (var assembly in scannedAssemblies) { nhibernateConfiguration.AddAssembly(assembly); } var modelMapper = new SagaModelMapper(typesToScan.Except(nhibernateConfiguration.ClassMappings.Select(x => x.MappedClass))); nhibernateConfiguration.AddMapping(modelMapper.Compile()); try { return(nhibernateConfiguration.BuildSessionFactory()); } catch (Exception e) { if (e.InnerException != null) { throw new ConfigurationErrorsException(e.InnerException.Message, e); } throw; } }
private static NhibConfigData GetOrCreateConfigData(String configFileName) { NhibConfigData retvalue = factories.SafeGet(configFileName); if (null == retvalue) { //This is the first time we ask for this configuration global::NHibernate.Cfg.Configuration config = new global::NHibernate.Cfg.Configuration(); XDocument doc = XDocument.Load(configFileName); XElement connStringElement = (from e in doc.Descendants() where e.Attribute("name") != null && e.Attribute("name").Value == "connection.connection_string" select e).Single(); String cnName = connStringElement.Value; connStringElement.Value = ConfigurationRegistry.ConnectionString(connStringElement.Value).ConnectionString; using (XmlReader reader = doc.CreateReader()) { config.Configure(reader); } ISessionFactory factory = config.BuildSessionFactory(); retvalue = new NhibConfigData() { Configuration = config, SessionFactory = factory, ConnectionName = cnName }; factories.Add(configFileName, retvalue); } return(retvalue); }
public void SetUp() { ConnectionString = $@"Data Source={Path.GetTempFileName()};New=True;"; var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary <string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, ConnectionString } }); var metaModel = new SagaMetadataCollection(); metaModel.Initialize(new[] { typeof(T) }); var metadata = metaModel.Find(typeof(T)); var modelMapper = new SagaModelMapper(metaModel, new[] { metadata.SagaEntityType }); configuration.AddMapping(modelMapper.Compile()); SessionFactory = configuration.BuildSessionFactory(); new SchemaUpdate(configuration).Execute(false, true); SagaPersister = new SagaPersister(); }
public void Setup() { var mapper = new ModelMapper(); mapper.AddMapping<OutboxEntityMap>(); var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary<string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString,connectionString } }); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaUpdate(configuration).Execute(false, true); SessionFactory = configuration.BuildSessionFactory(); Session = SessionFactory.OpenSession(); persister = new OutboxPersister { StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session), EndpointName = "TestEndpoint" }; }
public void Initialize(IContainer container) { var typeDiscoverer = container.Get<ITypeDiscoverer>(); FluentConfiguration.Mappings(m => DiscoverClassMapsAndAddAssemblies(typeDiscoverer, m)); Configuration = FluentConfiguration.BuildConfiguration(); SessionFactory = Configuration.BuildSessionFactory(); }
private void InsertInitialData(global::NHibernate.Cfg.Configuration configuration) { ISession session = configuration.BuildSessionFactory().OpenSession(); session.Save(LogBuilder.Default.Build()); session.Flush(); }
public void Setup() { var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary <string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, connectionString } }); var mapper = new ModelMapper(); mapper.AddMapping <TimeoutEntityMap>(); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaExport(configuration).Create(false, true); sessionFactory = configuration.BuildSessionFactory(); persister = new TimeoutPersister { SessionFactory = sessionFactory, DbConnectionProvider = new FakeDbConnectionProvider(sessionFactory.GetConnection()), EndpointName = "MyTestEndpoint" }; }
public void Setup() { var mapper = new ModelMapper(); mapper.AddMapping <OutboxEntityMap>(); var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary <string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, connectionString } }); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaUpdate(configuration).Execute(false, true); SessionFactory = configuration.BuildSessionFactory(); Session = SessionFactory.OpenSession(); persister = new OutboxPersister { StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session), EndpointName = "TestEndpoint" }; }
public void Initialize(IContainer container) { var typeDiscoverer = container.Get <ITypeDiscoverer>(); FluentConfiguration.Mappings(m => DiscoverClassMapsAndAddAssemblies(typeDiscoverer, m)); Configuration = FluentConfiguration.BuildConfiguration(); SessionFactory = Configuration.BuildSessionFactory(); }
/// <summary> /// Configures NHibernate /// </summary> public void Configure() { // Arashi.Core.NHibernate configuration = new Configuration(); configuration.Configure(); configuration = configuration.AddAssembly("Arashi.Core.NHibernate"); SessionFactory = configuration.BuildSessionFactory(); }
protected void InSession(Action <ISession> action) { var configuration = new global::NHibernate.Cfg.Configuration(); configuration.Configure(); ISessionFactory sessionFactory = configuration.BuildSessionFactory(); using (var session = sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { action(session); transaction.Commit(); } }
public void Setup() { var configuration = new global::NHibernate.Cfg.Configuration(); configuration.Configure(); sessionFactory = configuration.BuildSessionFactory(); if (!sessionFactory.Statistics.IsStatisticsEnabled) { Assert.Ignore("Statistics should be enabled"); } categoryRepository = new CategoryRepository(sessionFactory); }
public ISessionFactory GetSessionFactory(string connectionString, bool isDebug) { var configure = new global::NHibernate.Cfg.Configuration(); configure.DataBaseIntegration(db => { db.ConnectionString = connectionString; db.Driver <Driver.OracleDataClientDriver>(); db.Dialect <global::NHibernate.Dialect.Oracle10gDialect>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.LogFormattedSql = isDebug; db.LogSqlInConsole = isDebug; db.AutoCommentSql = false; }); return(configure.BuildSessionFactory()); }
private static ISessionFactory ByCodeMapped(INHibernateCodeConfig nhibernateConfiguration, Assembly assembly) { var mapper = new ModelMapper(); mapper.AddMappings(assembly.GetExportedTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(ClassMapping <>))); var configure = new global::NHibernate.Cfg.Configuration(); nhibernateConfiguration.AddDataBaseIntegrationInfo(configure); configure.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); return(configure.BuildSessionFactory()); }
public void Setup() { var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary <string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, connectionString } }); var mapper = new ModelMapper(); mapper.AddMapping <TimeoutEntityMap>(); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaExport(configuration).Create(false, true); sessionFactory = configuration.BuildSessionFactory(); persister = new TimeoutPersister("MyTestEndpoint", sessionFactory, new NHibernateSynchronizedStorageAdapter(sessionFactory), new NHibernateSynchronizedStorage(sessionFactory), TimeSpan.FromMinutes(2)); }
protected virtual ISessionFactory CreateFactory() { Logger.Info("Loading Configuration..."); try { var config = new global::NHibernate.Cfg.Configuration(); var strat = new EnhancedNamingStrategy { TablePrefix = Settings.TablePrefix }; config.SetNamingStrategy(strat); config.SetProperties(Settings.Properties); foreach (var directory in Settings.MappingDirectories) { var dir = new DirectoryInfo(directory); config.AddDirectory(dir); } foreach (var file in Settings.MappingFiles) { config.AddFile(file); } foreach (var assembly in Settings.MappingAssemblies) { config.AddAssembly(assembly); } return(config.BuildSessionFactory()); } catch (Exception x) { Logger.Error(x, "Error while loading configuration."); throw; } finally { Logger.Info("Configuration successfully loaded."); } }
internal static ISessionFactory CreateConfigurationForConfigFileName(string configurationFile) { try { global::NHibernate.Cfg.Configuration cfg = new global::NHibernate.Cfg.Configuration(); cfg.Configure(configurationFile); return(cfg.BuildSessionFactory()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("NHibernate exception stack"); String formatter = "--"; do { System.Diagnostics.Debug.WriteLine(formatter + ex.Message); ex = ex.InnerException; formatter += "--"; } while (ex != null); throw; } }
internal static ISessionFactory CreateConfigurationForConfigFileName(string configurationFile) { try { global::NHibernate.Cfg.Configuration cfg = new global::NHibernate.Cfg.Configuration(); cfg.Configure(configurationFile); return cfg.BuildSessionFactory(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("NHibernate exception stack"); String formatter = "--"; do { System.Diagnostics.Debug.WriteLine(formatter + ex.Message); ex = ex.InnerException; formatter += "--"; } while (ex != null); throw; } }
private void InsertInitialData(global::NHibernate.Cfg.Configuration configuration) { ISession session = configuration.BuildSessionFactory().OpenSession(); session.Save(BankBuilder.Default.Build()); session.Save(CustomerTypes.Bireysel); session.Save(CustomerTypes.Kurumsal); Customer customer = CustomerBuilder.Empty.WithName("Onur Eker").WithCustomerType(CustomerTypes.Bireysel).Build(); session.Save(customer); session.Flush(); Account account1 = AccountBuilder.Empty.WithName("Varsayılan Hesap").Build(); account1.Customer = customer; session.Save(account1); session.Flush(); Account account2 = AccountBuilder.Empty.WithName("USD Hesap").Build(); account2.Customer = customer; session.Save(account2); session.Flush(); customer.Accounts.Add(account1); customer.Accounts.Add(account2); customer.PrimaryAccount = account1; session.SaveOrUpdate(customer); session.Flush(); account1.Customer = customer; session.SaveOrUpdate(account1); account2.Customer = customer; session.SaveOrUpdate(account2); session.Flush(); }
public static ISessionFactory GetSessionFactory(HibernateDataContext cotnext) { var cfg = new global::NHibernate.Cfg.Configuration(); cfg.DataBaseIntegration(c => { c.ConnectionStringName = cotnext.ConnectionString; if (cotnext.Provider != null && cotnext.Provider.Equals("System.Data.SqlServerCe.4.0", StringComparison.OrdinalIgnoreCase)) { c.Driver <SqlServerCeDriver>(); c.Dialect <MsSqlCe40Dialect>(); } else { c.Driver <SqlClientDriver>(); c.Dialect <MsSql2008Dialect>(); } #if DEBUG c.LogFormattedSql = true; #endif c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; c.SchemaAction = SchemaAutoAction.Update; }); var mapper = new ModelMapper(); MapModels(mapper, cotnext.DbContext); cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); var result = cfg.BuildSessionFactory(); if (cotnext.BuildSchema) { BuildSchema(cfg); } if (cotnext.UpdateSchema) { UpdateSchema(cfg); } return(result); }
public void GenerateSchemaAndData() { var cfg = new global::NHibernate.Cfg.Configuration().Configure(); new SchemaExport(cfg) .SetDelimiter(";") .Execute(false, true, false); var random = new Random(); Func<DateTime> before2000 = () => new DateTime(random.Next(1950, 2000), random.Next(1, 13), random.Next(1, 29)); Func<DateTime> before2005 = () => new DateTime(random.Next(2000, 2005), random.Next(1, 13), random.Next(1, 29)); //some user data var users = new[] { new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User {Created = DateTime.Now, Email = "*****@*****.**", Username = "******" }, new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2000(), Email = "*****@*****.**", Username = "******" }, new User { Email = "*****@*****.**", Username = "******" }, new User { Email = "*****@*****.**", Username = "******" }, new User { Email = "*****@*****.**", Username = "******" }, new User { Email = "*****@*****.**", Username = "******" }, new User {Created = before2005(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2005(), Email = "*****@*****.**", Username = "******" }, new User {Created = before2005(), Email = "*****@*****.**", Username = "******" }, new User { Email = "*****@*****.**", Username = "******" }, }; using (var sessionFactory = cfg.BuildSessionFactory()) { using (var session = sessionFactory.OpenSession()) { using (var tx = session.BeginTransaction()) { var repo = new NHibernateRepository<User>(session); users.Walk(user => repo.Save(user)); tx.Commit(); } } } }
/// <summary> /// Returns the nhibernate session factory. /// </summary> /// <returns></returns> public ISessionFactory GetSessionFactory() { lock (lockO) { if (sessionFactory == null) { configuration = Fluently.Configure() .Database(OracleDataClientConfiguration.Oracle10 .ConnectionString(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString) .Dialect <Oracle10gDialect>() .Driver <OracleManagedDataClientDriver>() ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf <T>()).BuildConfiguration(); // new global::NHibernate.Tool.hbm2ddl.SchemaExport(configuration).Execute(false, true, false); sessionFactory = configuration.BuildSessionFactory(); } } return(sessionFactory); }
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()); }
public void Setup() { var configuration = new global::NHibernate.Cfg.Configuration() .AddProperties(new Dictionary<string, string> { { "dialect", dialect }, { global::NHibernate.Cfg.Environment.ConnectionString, connectionString } }); var mapper = new ModelMapper(); mapper.AddMapping<TimeoutEntityMap>(); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); new SchemaExport(configuration).Create(false, true); sessionFactory = configuration.BuildSessionFactory(); persister = new TimeoutPersister { SessionFactory = sessionFactory, DbConnectionProvider = new FakeDbConnectionProvider(sessionFactory.GetConnection()), EndpointName = "MyTestEndpoint" }; }
public void Configure() { Configuration = FluentConfiguration.BuildConfiguration(); SessionFactory = Configuration.BuildSessionFactory(); }
public static void Init(Action<global::NHibernate.Cfg.Configuration> exposedConfiguration = null) { lock (_syncRoot) { var automappingConfiguration = new XangoAutomapping(); XangoConfiguration xangoConfig = XangoConfigurationHelper.Get(); _configuration = Fluently.Configure() .Database(xangoConfig.Database) .ProxyFactoryFactory<ProxyFactoryFactory>() .CurrentSessionContext(xangoConfig.IsWeb ? "web" : "thread_static") .Mappings(mappings => mappings.AutoMappings.Add(AutoMap.Assembly(xangoConfig.DomainAssembly, automappingConfiguration) .UseOverridesFromAssembly(xangoConfig.OverrideMapAssembly ?? xangoConfig.DomainAssembly) .Conventions.Setup(conv => { conv.Add < CustomCollectionConvetion >(); conv.Add<CascadeAll>(); conv.Add < HiLoIndetityStrategy >(); conv.Add < TableNamePluralizeConvention >(); conv.Add < CustomForeignKeyConvention >(); }))) .ExposeConfiguration(Validation.NHFluentConfiguration.Initialize) .ExposeConfiguration(exposedConfiguration) .BuildConfiguration(); #if DEBUG var schema = new SchemaUpdate(_configuration); schema.Execute(true, true); #endif _sessionFactory = _configuration.BuildSessionFactory(); } }
public void Init() { MappingAssembly = GetType().Assembly; Mapper = new ConventionModelMapper(); Configuration = new global::NHibernate.Cfg.Configuration(); Mapper.IsPersistentId((m, declared) => declared || m.Name == "Id"); Mapper.BeforeMapBag += (inspector, member, customizer) => customizer.Key(k => k.Column(member.GetContainerEntity(inspector).Name + "Id")); Mapper.BeforeMapManyToOne += (inspector, member, customizer) => customizer.Column(member.LocalMember.Name + "Id"); Mapper.AfterMapProperty += (inspector, member, customizer) => { var propertyInfo = ((PropertyInfo)member.LocalMember); var propertyType = propertyInfo.PropertyType; if (typeof(ValueType).IsAssignableFrom(propertyType) && !propertyType.IsNullable()) { customizer.Column(c => c.Default(GetDefaultValue(propertyInfo))); customizer.NotNullable(true); } }; var simpleModelInspector = (SimpleModelInspector)Mapper.ModelInspector; simpleModelInspector.IsRootEntity((type, declared) => { var modelInspector = (IModelInspector)simpleModelInspector; return(declared || type.IsClass //если наследуемся от класса который не маплен то это простое наследование && (typeof(object) == type.BaseType || !modelInspector.IsEntity(type.BaseType)) && modelInspector.IsEntity(type)); }); var baseInspector = (IModelInspector) new SimpleModelInspector(); Mapper.IsEntity((type, declared) => { return(declared || baseInspector.IsEntity(type) || Configuration.ClassMappings.Any(m => m.MappedClass == type)); }); Configuration.AddProperties(new Dictionary <string, string> { { Environment.Dialect, "NHibernate.Dialect.MySQL5Dialect" }, { Environment.ConnectionDriver, "NHibernate.Driver.MySqlDataDriver" }, { Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider" }, { Environment.ConnectionStringName, "db" }, { Environment.Hbm2ddlKeyWords, "none" }, //раскомментировать если нужно отладить запросы хибера //{Environment.ShowSql, "true"}, //{Environment.FormatSql, "true"}, { Environment.Isolation, "ReadCommitted" }, }); Mapper.Class <Producer>(m => { m.Schema("catalogs"); }); Mapper.Class <Product>(m => { m.Id(s => s.Id); m.Schema("Catalogs"); m.Table("Products"); }); Mapper.Class <Catalog>(m => { m.Id(s => s.Id); m.Schema("Catalogs"); m.Table("Catalog"); m.ManyToOne(s => s.CatalogForm, mapper => mapper.Column("FormId")); m.ManyToOne(s => s.CatalogName, mapper => mapper.Column("NameId")); }); Mapper.Class <CatalogName>(m => { m.Id(s => s.Id); m.Schema("Catalogs"); m.Table("CatalogNames"); m.Bag(o => o.Catalogs, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("NameId")); }); m.ManyToOne(s => s.Mnn, mapper => mapper.Column("MnnId")); }); Mapper.Class <CatalogForm>(m => { m.Id(s => s.Id); m.Schema("Catalogs"); m.Table("CatalogForms"); }); Mapper.Class <Mnn>(m => { m.Id(s => s.Id); m.Schema("Catalogs"); m.Table("Mnn"); m.Property(x => x.Name, c => c.Column("Mnn")); }); Mapper.Class <Promoter>(m => { m.Bag(o => o.Associations, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); }); Mapper.Class <Association>(m => { m.ManyToOne(s => s.Supplier, mapper => mapper.Column("SupplierId")); m.Bag(o => o.Members, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); m.Bag(o => o.MarketingEvents, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); m.Bag(o => o.Promoters, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); m.Bag(o => o.Regions, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); m.Bag(o => o.Contacts, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); }); }); Mapper.Class <MarketingEvent>(m => { m.Bag(o => o.Producers, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("MarketingEventId")); }); m.Bag(o => o.Promotions, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("MarketingEventId")); }); }); Mapper.Class <PromoterProducer>(m => { m.ManyToOne(s => s.Producer, mapper => mapper.Column("ProducerId")); m.ManyToOne(s => s.MarketingEvent, mapper => mapper.Column("MarketingEventId")); }); Mapper.Class <PromotionMember>(m => { m.Bag(o => o.Subscribes, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("MemberId")); }); m.Bag(o => o.AddressLimits, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("MemberId")); }); m.Bag(o => o.LegalEntityLimits, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("MemberId")); }); }); Mapper.Class <AddressLimit>(m => { m.ManyToOne(s => s.Member, mapper => mapper.Column("MemberId")); m.ManyToOne(s => s.Address, mapper => mapper.Column("AddressId")); }); Mapper.Class <LegalEntityLimit>(m => { m.ManyToOne(s => s.Member, mapper => mapper.Column("MemberId")); m.ManyToOne(s => s.LegalEntity, mapper => mapper.Column("LegalEntityId")); }); Mapper.Class <PromotionProduct>(m => { m.ManyToOne(s => s.Product, mapper => mapper.ForeignKey("ProductId")); m.ManyToOne(s => s.Promotion, mapper => mapper.ForeignKey("PromotionId")); m.Bag(o => o.Replacements, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => k.Column("PromotionProductId")); }); }); Mapper.Class <PromotionReplacement>(m => { m.ManyToOne(s => s.Catalog, mapper => mapper.Column("CatalogId")); }); Mapper.Class <PromotionSupplier>(m => { m.ManyToOne(s => s.Supplier, mapper => mapper.ForeignKey("SupplierId")); m.ManyToOne(s => s.Promotion, mapper => mapper.ForeignKey("PromotionId")); }); Mapper.Class <ProducerPromotion>(m => { m.ManyToOne(s => s.MarketingEvent, mapper => mapper.Column("MarketingEventId")); m.Bag(o => o.Products, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(s => s.Column("PromotionId")); }, map => map.OneToMany(s => s.Class(typeof(PromotionProduct)))); m.Bag(o => o.Suppliers, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(s => s.Column("PromotionId")); }, map => map.OneToMany(s => s.Class(typeof(PromotionSupplier)))); m.Bag(o => o.Subscribes, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(s => s.Column("PromotionId")); }, map => map.OneToMany(s => s.Class(typeof(PromotionSubscribe)))); m.Bag(o => o.FeePercents, c => { c.Cascade(Cascade.All); c.Inverse(true); c.Key(s => s.Column("PromotionId")); }); m.Bag(o => o.FeeSums, c => { c.Cascade(Cascade.All); c.Inverse(true); c.Key(s => s.Column("PromotionId")); }); }); Mapper.Class <PromotionPercent>(m => { m.ManyToOne(s => s.Promotion, mapper => mapper.Column("PromotionId")); }); Mapper.Class <PromotionSum>(m => { m.ManyToOne(s => s.Promotion, mapper => mapper.Column("PromotionId")); }); Mapper.Class <PromotionSubscribe>(m => { m.ManyToOne(s => s.Member, mapper => mapper.Column("MemberId")); m.ManyToOne(s => s.Promotion, mapper => mapper.Column("PromotionId")); }); Mapper.Class <Address>(m => { m.Property(x => x.AddressName, c => c.Column("Address")); }); Mapper.Class <RegionalAdmin>(m => { m.Schema("AccessRight"); m.Table("RegionalAdmins"); m.Id(x => x.RowId); m.Property(x => x.Name, c => c.Column("UserName")); }); Mapper.Class <Region>(m => { m.Schema("Farm"); m.Table("Regions"); m.Id(x => x.Id, mapper => mapper.Column("RegionCode")); m.Property(x => x.Name, mapper => mapper.Column("Region")); }); Mapper.Class <Client>(m => { m.ManyToOne(c => c.Region, mapper => mapper.Column("RegionCode")); m.Bag(o => o.ContactGroups, c => { c.Cascade(Cascade.None); c.Inverse(true); c.Key(k => { k.PropertyRef(x => x.ContactGroupOwnerId); k.Column("ContactGroupOwnerId"); }); }); m.Bag(o => o.Payers, c => { c.Cascade(Cascade.None); c.Inverse(true); c.Key(s => s.Column("ClientId")); }); }); Mapper.Class <PayerClient>(m => { m.ManyToOne(c => c.Client, mapper => mapper.Column("ClientId")); m.ManyToOne(c => c.Payer, mapper => mapper.Column("PayerId")); }); Mapper.Class <Payer>(m => { m.Id(x => x.Id, mapper => mapper.Column("PayerID")); m.Schema("Billing"); m.Table("Payers"); m.Bag(o => o.LegalEntities, c => { c.Cascade(Cascade.None); c.Inverse(true); c.Key(s => s.Column("PayerId")); }); }); Mapper.Class <LegalEntity>(m => { m.Schema("Billing"); m.Table("LegalEntities"); m.ManyToOne(c => c.Payer, mapper => mapper.Column("PayerId")); }); Mapper.Class <Contact>(m => { m.Schema("Contacts"); m.Table("Contacts"); m.Property(x => x.ContactType, mapper => mapper.Column("Type")); }); Mapper.Class <ContactGroup>(m => { m.Id(x => x.Id, mapper => mapper.Generator(new AssignedGeneratorDef())); m.Schema("Contacts"); m.Table("Contact_groups"); m.Property(x => x.ContactGroupTypeId, mapper => mapper.Column("Type")); m.Bag(o => o.Contacts, c => { c.Cascade(Cascade.All | Cascade.DeleteOrphans); c.Inverse(true); c.Key(k => { k.PropertyRef(x => x.Id); k.Column("ContactOwnerId"); }); }); }); Mapper.Class <ContactOwner>(m => { m.Schema("Contacts"); m.Table("Contact_owners"); }); Mapper.Class <ContactGroupOwner>(m => { m.Schema("Contacts"); m.Table("Contact_group_owners"); }); var types = MappingAssembly.GetTypes().Where(t => !Attribute.IsDefined(t, typeof(CompilerGeneratedAttribute), false) && Mapper.ModelInspector.IsRootEntity(t)); var mapping = Mapper.CompileMappingFor(types.Distinct()); var @class = Generators.Native.Class; foreach (var rootClass in mapping.RootClasses.Where(c => c.Id != null)) { if (rootClass.Id.generator == null) { rootClass.Id.generator = new HbmGenerator { @class = @class }; } } Configuration.SetNamingStrategy(new PluralizeNamingStrategy()); Configuration.AddDeserializedMapping(mapping, MappingAssembly.GetName().Name); Factory = Configuration.BuildSessionFactory(); }
private static NhibConfigData GetOrCreateConfigData(String configFileName) { NhibConfigData retvalue = factories.SafeGet(configFileName); if (null == retvalue) { //This is the first time we ask for this configuration global::NHibernate.Cfg.Configuration config = new global::NHibernate.Cfg.Configuration(); XDocument doc = XDocument.Load(configFileName); XElement connStringElement = (from e in doc.Descendants() where e.Attribute("name") != null && e.Attribute("name").Value == "connection.connection_string" select e).Single(); String cnName = connStringElement.Value; connStringElement.Value = ConfigurationRegistry.ConnectionString(connStringElement.Value).ConnectionString; using (XmlReader reader = doc.CreateReader()) { config.Configure(reader); } ISessionFactory factory = config.BuildSessionFactory(); retvalue = new NhibConfigData() { Configuration = config, SessionFactory = factory, ConnectionName = cnName }; factories.Add(configFileName, retvalue); } return retvalue; }
static NHibernateHelper() { _configuration = new global::NHibernate.Cfg.Configuration(); _configuration.AddAssembly(Config.NhibernateAssembly); _sessionFactory = _configuration.BuildSessionFactory(); }
private ISessionFactory GenerateNHibernateSessionFactory() { var sw = Stopwatch.StartNew(); ForceLoadObjectModel(); // This is needed for "new Configuration()". var configuration = new global::NHibernate.Cfg.Configuration(); configuration.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider"); configuration.SetProperty("connection.connection_string", _connectionString); // Set factory-level property: configuration.SetProperty("command_timeout", SqlUtility.SqlCommandTimeout.ToString()); // Set system-level property: // Note: Using NHibernate.Cfg.Environment.Properties does not allow setting properties becase the public property returns a copy of the dictionary. var globalPropertiesField = typeof(global::NHibernate.Cfg.Environment).GetField("GlobalProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); var globalProperties = (Dictionary<string, string>)globalPropertiesField.GetValue(null); globalProperties.Add("command_timeout", SqlUtility.SqlCommandTimeout.ToString()); if (SqlUtility.DatabaseLanguage == "MsSql") { configuration.SetProperty("dialect", "NHibernate.Dialect.MsSql2005Dialect"); configuration.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver"); } else if (SqlUtility.DatabaseLanguage == "Oracle") { configuration.SetProperty("dialect", "NHibernate.Dialect.Oracle10gDialect"); configuration.SetProperty("connection.driver_class", "NHibernate.Driver.OracleDataClientDriver"); } else throw new FrameworkException(DatabaseLanguageError); ResolveEventHandler resolveAssembly = (s, args) => _domainObjectModel.Assembly; try { AppDomain.CurrentDomain.AssemblyResolve += resolveAssembly; configuration.AddXmlString(_nHibernateMapping.GetMapping()); } finally { AppDomain.CurrentDomain.AssemblyResolve -= resolveAssembly; } foreach (var configurationExtension in _nHibernateConfigurationExtensions) configurationExtension.ExtendConfiguration(configuration); SchemaMetadataUpdater.QuoteTableAndColumns(configuration); var sessionFactory = configuration.BuildSessionFactory(); _performanceLogger.Write(sw, "NHibernatePersistenceEngine.PrepareNHSessionFactory"); return sessionFactory; }
//[Fact] public async Task ConstructDynamicEntity_Test() { try { const string firstNamePropName = "FirstName"; var dynamicEntityMeta = new DynamicEntity { Name = "DynamicPerson", Properties = new DynamicPropertyList { { "Id", typeof(Guid) }, { firstNamePropName, typeof(string) }, { "LastName", typeof(string) }, { "Age", typeof(int) }, { "BirthDate", typeof(DateTime?) }, } }; var dynamicPersonType = ShaEntityTypeBuilder.CompileResultType(dynamicEntityMeta); var dynamicPerson = Activator.CreateInstance(dynamicPersonType); dynamicPerson.ShouldNotBeNull(); var firstNameTestValue = "John"; var propInfo = dynamicPerson.GetType().GetProperty(firstNamePropName); propInfo.SetValue(dynamicPerson, firstNameTestValue); var firstNameValue = propInfo.GetValue(dynamicPerson); firstNameValue.ShouldBe(firstNameTestValue); var nhConfig = new global::NHibernate.Cfg.Configuration(); nhConfig.DataBaseIntegration(db => { db.ConnectionString = @"Data Source=.\sql2019;Initial Catalog=SheshaDemo;Integrated Security=True"; db.Dialect <MsSql2012Dialect>(); db.Driver <Sql2008ClientDriver>(); db.Timeout = 150; db.LogFormattedSql = true; }) .SetProperty("hbm2ddl.keywords", "auto-quote") .CurrentSessionContext <UnitOfWorkSessionContext>(); // register filters nhConfig.AddFilterDefinition(SoftDeleteFilter.GetDefinition()); nhConfig.AddFilterDefinition(MayHaveTenantFilter.GetDefinition()); nhConfig.AddFilterDefinition(MustHaveTenantFilter.GetDefinition()); var conventions = new Conventions(); var dynamicPersonAssembly = dynamicPerson.GetType().Assembly; conventions.AddAssembly(dynamicPersonAssembly, "Test_"); conventions.Compile(nhConfig); var sessionFactory = nhConfig.BuildSessionFactory(); var migrationsGenerator = LocalIocManager.Resolve <IMigrationGenerator>(); var migration = migrationsGenerator.GenerateMigrations(new List <Type> { dynamicPersonType }); using (var session = sessionFactory.OpenSession()) { // save our person session.SaveOrUpdate(dynamicPerson); session.Flush(); var person = dynamicPerson as Entity <Guid>; person.ShouldNotBeNull(); person.Id.ShouldNotBe(Guid.Empty); var query = session.CreateQuery($"select ent from {dynamicPersonType.FullName} ent"); var items = query.List(); items.Count.ShouldBeGreaterThan(0); var fetchedPerson = session.Get(dynamicPersonType, person.Id) as Entity <Guid>; fetchedPerson.ShouldNotBeNull(); fetchedPerson.Id.ShouldBe(person.Id); } } catch (Exception e) { throw; } }