private static ISessionFactory createSessionFactory() { var configure = new Configuration(); configure.SessionFactoryName(sessionName); configure.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = sessionName; db.Timeout = 10; }); // mapping by code var mapper = new ModelMapper(); mapper.AddMappings(Assembly.GetExecutingAssembly() .GetExportedTypes()); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); // mapping by xml configure.AddAssembly("MITD.PMS.Persistence.NH"); //Other setting configure.AddDeserializedMapping(mapping, sessionName); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure.BuildSessionFactory()); }
static NHibernateHelper() { try { cfg = new Configuration(); cfg.Configure("NHibernateQueryModelConfiguration.xml"); var mapper = new ConventionModelMapper(); //mapper.IsEntity((t, declared) => t.Namespace.StartsWith("Sample.QueryModel") || ); mapper.AfterMapClass += (inspector, type, classCustomizer) => { classCustomizer.Lazy(false); //classCustomizer.Id(m => m.Generator(new GuidGeneratorDef())); }; var mapping = mapper.CompileMappingFor( Assembly.Load("Sample.QueryModel").GetExportedTypes() .Union(new Type[] { typeof(Version) })); var allmapping = mapping.AsString(); cfg.AddDeserializedMapping(mapping, "AutoModel"); _sessionFactory = cfg.BuildSessionFactory(); } catch (Exception ex) { throw ex; } }
private static void InitNHibernate() { lock (LockObject) { if (_sessionFactory == null) { // Создание NHibernate-конфигурации приложения на основании описаний из web.config. // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, // заданные в xml-файлах. var configure = new Configuration().Configure(); // Настройка маппинга, созданного при помощи mapping-by-code var mapper = new ModelMapper(); mapper.AddMappings(new List<Type> { // Перечень классов, описывающих маппинг typeof (DocumentTypeMap), typeof (DocumentMap), typeof (DocumentWithVersionMap), }); // Добавление маппинга, созданного при помощи mapping-by-code, // в NHibernate-конфигурацию приложения configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null); //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>(); //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>(); configure.DataBaseIntegration(x => { x.LogSqlInConsole = true; x.LogFormattedSql = true; }); _sessionFactory = configure.BuildSessionFactory(); } } }
static void Main(string[] args) { var configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.ConnectionString = @"Server=.\sqlexpress;initial catalog=NHibernateTest;Integrated Security=true;"; db.Dialect <MsSql2012Dialect>(); db.Driver <SqlClientDriver>(); }); var modelMapper = new ModelMapper(); modelMapper.AddMapping <PersonMapping>(); modelMapper.AddMapping <CarMapping>(); var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(mapping, "Test"); var schema = new SchemaExport(configuration); // schema.Execute(false, true, false); ejecutar solo la primera vez //paso 1 //insertarDatos(configuration); //paso 2 //verDatos(configuration); // paso 3 // actualizarDatos(configuration) // paso 4 // deleteDatos(configuration); }
/// <summary> /// Configure NHibernate /// </summary> private static Configuration ConfigureNHibernate() { Configuration configure = new Configuration(); configure.SessionFactoryName("SessionFactory"); configure.DataBaseIntegration(db => { db.Dialect <MsSql2008Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = RegtestingServerConfiguration.DefaultConnectionString; //db.Timeout = 10; //For testing //db.LogFormattedSql = true; //db.LogSqlInConsole = true; //db.AutoCommentSql = true; }); HbmMapping hbmMapping = GetMappings(); configure.AddDeserializedMapping(hbmMapping, "NHMapping"); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var types = new List <Type>() { typeof(Color3Map) }; var mapper = new ModelMapper(); mapper.AddMappings(types); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.ConnectionString = "host=localhost;database=sandbox;user id=postgres;password=Asztal15"; db.Driver <NpgsqlDriver>(); db.Dialect <PostgreSQLDialect>(); db.LogFormattedSql = true; db.LogSqlInConsole = true; }); configuration.SetNamingStrategy(DbNamingStrategy.Instance); // add before mappings! // add xml configs: configuration.AddAssembly(Assembly.GetExecutingAssembly()); configuration.AddDeserializedMapping(mapping, null); //SchemaMetadataUpdater.QuoteTableAndColumns(configuration); //configuration.SetProperty("hbm2ddl.keywords", "auto-quote"); var sefact = configuration.BuildSessionFactory(); using (var session = sefact.OpenSession()) { //var colors = session.Query<Color3>().Where(r => r.Id > 0).ToList(); //var newCol = new Color3 { Name = "new1" }; //session.Save(newCol); } using (var session = sefact.OpenSession()) { var newCol = new Color3 { Name = "new1" }; var ret = session.Save(newCol); Console.WriteLine(ret.ToString()); } using (var session = sefact.OpenStatelessSession()) { var newCol = new Color3 { Name = "new1" }; var ret = session.Insert(newCol); Console.WriteLine(ret.ToString()); } Console.ReadLine(); }
protected override void AddMappings(Configuration configuration) { var mapper = new ModelMapper(); mapper.Class <Employee>(mc => { mc.Id(x => x.Id, map => { map.Generator(Generators.Increment); map.Column("Id"); }); mc.ManyToOne <EmployeeInfo>(x => x.Info, map => { map.Column("Info_id"); map.Unique(true); map.Cascade(Mapping.ByCode.Cascade.All | Mapping.ByCode.Cascade.DeleteOrphans); }); mc.Property(x => x.Name); }); mapper.Class <EmployeeInfo>(cm => { cm.Id(x => x.Id, m => { m.Generator(Generators.Increment); m.Column("Id"); }); cm.OneToOne <Employee>(x => x.EmployeeDetails, map => { map.PropertyReference(x => x.Info); }); cm.Property(x => x.JobTitle); }); configuration.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "TestDomain"); }
public void SetUp() { var configuration = new Configuration(); configuration .SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true") .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, "create-drop") .SetProperty(NHibernate.Cfg.Environment.UseQueryCache, "true") .SetProperty(NHibernate.Cfg.Environment.CacheProvider, typeof(HashtableCacheProvider).AssemblyQualifiedName) .SetProperty(NHibernate.Cfg.Environment.ReleaseConnections, "on_close") .SetProperty(NHibernate.Cfg.Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName) .SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName) .SetProperty(NHibernate.Cfg.Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;"); var assembly = Assembly.GetExecutingAssembly(); var modelMapper = new ModelMapper(); modelMapper.AddMappings(assembly.GetTypes()); var hbms = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(hbms, assembly.GetName().Name); ConfigureSearch(configuration); sessionFactory = configuration.BuildSessionFactory(); Session = sessionFactory.OpenSession(); SearchSession = Search.CreateFullTextSession(Session); new SchemaExport(configuration) .Execute(false, true, false, Session.Connection, null); AfterSetup(); }
public ISessionFactory CriaSessionFactoryNHibernate() { _bancoDeDados = BancoDeDados.Postgresql; var cfg = new Configuration(); if (_bancoDeDados == BancoDeDados.Postgresql) { cfg.SetNamingStrategy(new PostgreSqlNamingStrategy()); } var assembly = Assembly.GetAssembly(GetType()); var mappingClass = ObterMapemanetoDeClasses(); cfg.AddProperties(ObterPropriedades()); cfg.AddAssembly(assembly); cfg.AddAssembly(Assembly.GetAssembly(typeof(Usuario))); cfg.AddDeserializedMapping(mappingClass, assembly.GetName().Name); var iSessionFactory = cfg.BuildSessionFactory(); return(iSessionFactory); }
protected override void BuildMappings(Configuration conf) { HbmMapping mapping = GetMappings(); conf.AddDeserializedMapping(mapping, "NHSchemaTest"); SchemaMetadataUpdater.QuoteTableAndColumns(conf); }
public static ISessionFactory Create(Assembly mappingAssembly, string connectionString) { var configuration = new Configuration(); configuration.SessionFactoryName("AuctionManagement"); configuration.DataBaseIntegration(db => { db.Dialect <MsSql2012Dialect>(); db.Driver <SqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = connectionString; db.Timeout = 30; }); configuration.AddAssembly(mappingAssembly); var modelMapper = new ModelMapper(); modelMapper.BeforeMapClass += (mi, t, map) => map.DynamicUpdate(true); modelMapper.AddMappings(mappingAssembly.GetExportedTypes()); var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(mappingDocument, "AuctionManagement"); AddDomainEventListeners(configuration); return(configuration.BuildSessionFactory()); }
public void Script() { var automapper = new AutoMapper { EntityBaseType = typeof(AutoMapperTestEntityBase) }; automapper.MapAssemblyOf <SchemaTests>(); var compiled = automapper.Complete(); var configuration = new Configuration(); configuration.DataBaseIntegration(db => { db.Dialect <SQLiteDialect>(); db.ConnectionString = "Data Source=:memory:;Version=3;New=True"; }); configuration.AddDeserializedMapping(compiled.First(), string.Empty); var export = new SchemaExport(configuration); export.Execute(true, false, false); }
private static Configuration GetConfiguration() { var serializer = new HbmSerializer { Validate = true }; var cfg = new Configuration(); cfg.SetInterceptor(new GenericInterceptor(TypeManager.Instance)); cfg.DataBaseIntegration(db => { db.ConnectionStringName = ConnectionStringName; db.Dialect <NHibernate.Dialect.MySQL55Dialect>(); db.Driver <NHibernate.Driver.MySqlDataDriver>(); db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'"; db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.SchemaAction = SchemaAutoAction.Validate; }); var mapper = new ModelMapper(); mapper.AddMappings(ClassMappingManager.Instance.ClassMappings); var mappings = mapper.CompileMappingForAllExplicitlyAddedEntities(); cfg.AddDeserializedMapping(mappings, null); return(cfg); }
private static void BuildSessionFactory(string userName, string connectionString) { var currentAssembly = typeof(NHibernateSessionFactory).Assembly; var manifestName = currentAssembly.ManifestModule.Name.Replace(".dll", string.Empty); var configuration = new Configuration(); configuration.SetProperty(Environment.ConnectionString, connectionString); configuration.Configure(currentAssembly, $"{manifestName}.NHibernate.hibernate.cfg.xml"); configuration.AddAssembly(currentAssembly); configuration.SetProperty(Environment.UseSqlComments, "false"); var mappings = GetMappings(); configuration.AddDeserializedMapping(mappings, manifestName); SchemaMetadataUpdater.QuoteTableAndColumns(configuration); configuration.DataBaseIntegration(db => { db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); SessionFactoryCache.Add(userName, configuration.BuildSessionFactory()); }
/// <summary> /// 数据初始化 /// </summary> /// <param name="inputConfiguartionPacker"></param> /// <param name="lstTypeNeedMap"></param> private void PrepareData(ConfigurationPacker inputConfiguartionPacker, List <Type> lstTypeNeedMap) { m_hibernateConfig = new Configuration(); m_useConfiguartionPacker = inputConfiguartionPacker; m_useAutoMappingHandler = new EntityAutoMappingHandler(); Type baseType = typeof(BaseEntity); //过滤基类 var useFullType = from n in lstTypeNeedMap where baseType.IsAssignableFrom(n) select n; foreach (var oneType in useFullType) { m_useAutoMappingHandler.RegiesType(oneType); } //获得映射 var useHbm = m_useAutoMappingHandler.GetHbmMapping(); //设置配置 m_useConfiguartionPacker.AddToNHibernateConfiguration(m_hibernateConfig); //注册映射 m_hibernateConfig.AddDeserializedMapping(useHbm, Guid.NewGuid().ToString()); //创建会话工厂 m_useSessionFactory = m_hibernateConfig.BuildSessionFactory(); }
public static Configuration Init( ISessionStorage storage, string cfgFile, IDictionary <string, string> cfgProperties, string validatorCfgFile, params HbmMapping[] mapping) { NHibernateSession.InitStorage(storage); var config = new Configuration(); if (cfgProperties != null) { config.AddProperties(cfgProperties); } if (string.IsNullOrEmpty(cfgFile) == false) { config.Configure(cfgFile); } else { config.Configure(); } foreach (var map in mapping) { config.AddDeserializedMapping(map, null); } return(NHibernateSession.AddConfiguration(NHibernateSession.DefaultFactoryKey, config.BuildSessionFactory(), config, validatorCfgFile)); }
public ISessionFactory Build() { var configuration = new Configuration(); configuration.SessionFactoryName(_sessionFactoryName); configuration.DataBaseIntegration(db => { db.Dialect <MsSql2012Dialect>(); db.Driver <YekeSqlClientDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = ConnectionString; db.Timeout = 30; }); configuration.AddAssembly(_mappingAssembly); var modelMapper = new ModelMapper(); modelMapper.BeforeMapClass += (mi, t, map) => map.DynamicUpdate(true); modelMapper.AddMappings(_mappingAssembly.GetExportedTypes()); AddDomainEventListener(configuration); var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(mappingDocument, _sessionFactoryName); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, new MsSql2012Dialect()); return(configuration.BuildSessionFactory()); }
private static Configuration ConfigureNHibernate() { var configure = new Configuration(); configure.SessionFactoryName("BuildIt"); configure.DataBaseIntegration(db => { db.Dialect <MySQL5Dialect>(); db.Driver <MySqlDataDriver>(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionStringName = "NHV2"; db.Timeout = 15; // enabled for testing db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); var mapping = GetMappings(); configure.AddDeserializedMapping(mapping, "NHibernateV2"); SchemaMetadataUpdater.QuoteTableAndColumns(configure); return(configure); }
public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration) { Type baseEntityType = typeof(Entity); mapper.IsEntity((type, declared) => IsEntity(type)); mapper.IsRootEntity((type, declared) => baseEntityType.Equals(type.BaseType)); mapper.BeforeMapClass += (modelInspector, type, classCustomizer) => { classCustomizer.Id(c => c.Column("Id")); classCustomizer.Id(c => c.Generator(Generators.Identity)); classCustomizer.Table(Inflector.Net.Inflector.Pluralize(type.Name.ToString())); }; mapper.BeforeMapManyToOne += (modelInspector, propertyPath, map) => { map.Column(propertyPath.LocalMember.GetPropertyOrFieldType().Name + "Fk"); map.Cascade(Cascade.Persist); }; mapper.BeforeMapBag += (modelInspector, propertyPath, map) => { map.Key(keyMapper => keyMapper.Column(propertyPath.GetContainerEntity(modelInspector).Name + "Fk")); map.Cascade(Cascade.All); }; AddConventionOverrides(mapper); HbmMapping mapping = mapper.CompileMappingFor(typeof(Customer).Assembly.GetExportedTypes().Where(t => IsEntity(t))); configuration.AddDeserializedMapping(mapping, "MyStoreMappings"); }
private static Configuration CreateConfiguration(String configFile) { Configuration configuration = new Configuration(); configuration.Configure(configFile); configuration.AddDeserializedMapping(Mapping, null); return(configuration); }
private static Configuration CreateConfiguration() { var configuration = new Configuration(); configuration.Configure(); configuration.AddDeserializedMapping(Mapping, null); return(configuration); }
public void Configure(Configuration configuration) { var conventions = this.conventionTypes.Select(c => Activator.CreateInstance(c, true)).ToList(); var mapper = new ModelMapper(); mapper.BeforeMapProperty += (inspector, member, customizer) => { foreach (var convention in conventions.OfType <IPropertyConvention>()) { if (convention.Accept(member)) { convention.Apply(customizer); } } }; foreach (var assembly in this.configurationAssemblies) { var types = assembly.GetExportedTypes().Select(c => new { Type = c, Order = GetMappingOrder(c) }).ToList(); var orders = types.Select(c => c.Order).Distinct().OrderBy(c => c); foreach (var order in orders) { var safeOrder = order; mapper.AddMappings(types.Where(c => c.Order == safeOrder).Select(c => c.Type)); } } var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); configuration.AddDeserializedMapping(mapping, this.GetType().Name); foreach (var classMapping in configuration.ClassMappings) { if (classMapping.Version == null) { continue; } var column = classMapping.Version.ColumnIterator.Cast <Column>().First(); var customType = column.Value.Type as CustomType; if (customType != null && customType.UserType is RowVersionType) { // TODO: This is SQL Server specific column.SqlType = "rowversion"; } } configuration.Cache(c => { c.Provider <RtMemoryCacheProvider>(); c.UseQueryCache = true; }); }
public void SchemaExport() { Configuration conf = ConfigureNHibernate(); conf.AddDeserializedMapping(GetMapping(), "Animals_Domain"); SchemaMetadataUpdater.QuoteTableAndColumns(conf); ActionAssert.NotThrow(() => new SchemaExport(conf).Create(false, true)); new SchemaExport(conf).Drop(false, true); }
public static void Setup() { NHConfiguration = configureNHibernate(); HbmMapping mapping = getMappings(); NHConfiguration.AddDeserializedMapping(mapping, "NHibernate32Test"); SchemaMetadataUpdater.QuoteTableAndColumns(NHConfiguration); SessionFactory = NHConfiguration.BuildSessionFactory(); }
public NhibernateHelper(IDatabaseProvider databaseProvider, HbmMapping mapping, IConfigurationApplier configurationApplier) { configurationApplier.Apply(Configuration, databaseProvider); Configuration.AddDeserializedMapping(mapping, null); databaseSchema = new NhibernateDatabaseSchema(databaseProvider, configuration); ExecuteSchemaAction(configurationApplier.SchemaAction, databaseSchema); }
private static ISessionFactory CreateSessionFactoryFor(string[] mappingsAssemblies, Configuration cfg) { var assemblies = new List <Assembly>(); Array.ForEach(mappingsAssemblies, i => assemblies.Add(Assembly.LoadFrom(MakeLoadReadyAssemblyName(i)))); var mapping = GetMappings(assemblies); cfg.AddDeserializedMapping(mapping, null); return(cfg.BuildSessionFactory()); }
private static Configuration CreateConfiguration() { var configuration = new Configuration(); //Loads properties from hibernate.cfg.xml configuration.Configure(); //Loads nhibernate mappings configuration.AddDeserializedMapping(CreateMapping(), null); return(configuration); }
public PessoaRepositorio() { Configuration config = new Configuration(); config.Configure(); config.AddAssembly(typeof(Pessoa).Assembly); HbmMapping mapping = CreateMappings(); config.AddDeserializedMapping(mapping, null); _sessionFactory = config.BuildSessionFactory(); }
public static void Setup() { myConfiguration = NhiberanteConfigure(); HbmMapping mapping = GetMappings(); myConfiguration.AddDeserializedMapping(mapping, "NHSchema"); SchemaMetadataUpdater.QuoteTableAndColumns(myConfiguration); mySessionFactory = myConfiguration.BuildSessionFactory(); OpenSession(); }
public ISessionFactory GetSessionFactory() { Configuration cfg = ConfigureNHibernateFromConfigFile(); // OR ConfigureNHibernate (); HbmMapping mapping = GetMappings(); cfg.AddDeserializedMapping(mapping, "BackendDotNet.Library.Schema"); SchemaMetadataUpdater.QuoteTableAndColumns(cfg); ISessionFactory sessionFactory = cfg.BuildSessionFactory(); return(sessionFactory); }