protected override void PostProcessConfiguration(global::NHibernate.Cfg.Configuration config) { base.PostProcessConfiguration(config); if (FluentNhibernateMappingAssemblies != null) { // add any class mappings in the listed assemblies: var mapper = new ModelMapper(); foreach (var asm in FluentNhibernateMappingAssemblies.Select(Assembly.Load)) { mapper.AddMappings(asm.GetTypes()); } foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity()) { config.AddMapping(mapping); } foreach (string assemblyName in FluentNhibernateMappingAssemblies) { config.AddMappingsFromAssembly(Assembly.Load(assemblyName)); } } }
static void Main(string[] args) { Configuration config = new Configuration(); config.Configure(); var mapper = new ModelMapper(); mapper.AddMappings(typeof(StudentMap).Assembly.GetTypes()); mapper.AddMappings(typeof(ZorgIfmTariefMap).Assembly.GetTypes()); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var xml = mapping.AsString(); config.AddAssembly(typeof(ZorgIfmTarief).Assembly); ISessionFactory sf = config.BuildSessionFactory(); ISession session = sf.OpenSession(); var list = session.QueryOver <Student>() .Where(student => student.ID > 1) .Take(10) .List <Student>(); foreach (var tar in list) { Console.WriteLine(tar.FirstMidName); } }
public static ISessionFactory GetOrCreateSessionFactory() { if (_sessionFactory != null) { return(_sessionFactory); } var cfg = new Configuration(); // настройка подключения к БД cfg.DataBaseIntegration(d => { // диалект контролирует синтаксис sql-запросов d.Dialect <NHibernate.Dialect.PostgreSQLDialect>(); // драйвер отвечает за отправку и прием данных d.Driver <NHibernate.Driver.NpgsqlDriver>(); d.ConnectionString = "Server=localhost;Port=5432;Database=library;User ID=postgres;Password=123"; d.LogSqlInConsole = true; }); var oldListenets = cfg.EventListeners.FlushEventListeners.ToList(); oldListenets.Add(new FlushEventListener()); cfg.EventListeners.FlushEventListeners = oldListenets.ToArray(); // указываем маппинги сущностей var modelMapper = new ModelMapper(); Assembly.Load("EntitiesAndMaps"); var mapTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetExportedTypes()) .Where(type => type.IsClass) .Where(type => type.BaseType != null) .Where(type => type.BaseType.IsGenericType) .Where(type => typeof(ClassMapping <>) == type.BaseType.GetGenericTypeDefinition()) .ToArray(); foreach (var mapType in mapTypes) { modelMapper.AddMapping(mapType); } cfg.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities()); modelMapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); // создаем объект ISessionFactory, хранящий в себе настройки, в единственном экземпляре // этот объект не содержит подключения к БД var sessionFactory = cfg.BuildSessionFactory(); _sessionFactory = sessionFactory; return(_sessionFactory); }
public void CanWriteMappingsReferencingProtectedProperty() { var mapper = new ModelMapper(); mapper.Class <Entity>(rc => { rc.Id(Entity.PropertyAccessExpressions.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); }); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); }
private IEnumerable<HbmMapping> CreateMapper() { var mapper = new ModelMapper(); mapper.AddMapping<XmlAsStringEntityMap>(); mapper.AddMapping<XmlEntityMap>(); mapper.AddMapping<BinaryEntityMap>(); mapper.AddMapping<ProtobufEntityMap>(); mapper.AddMapping<JsonEntityMap>(); return mapper.CompileMappingForEachExplicitlyAddedEntity(); }
/// <summary> /// 构造器 /// </summary> public SessionManager(Assembly[] assemblies) { //通过Mapping by code加载映射 var mapper = new ModelMapper(); foreach (var assembly in assemblies) { try { mapper.AddMappings(assembly.GetExportedTypes()); } catch (Exception e) { //有些程序集里不包含NH配置信息,会抛异常,捕获但不处理 } } //This will write all the XML into the bin/mappings folder if (HttpContext.Current == null) { mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); } var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); var configure = new Configuration(); configure.Configure(); configure.AddDeserializedMapping(hbmMapping, ""); configure.CurrentSessionContext <WebSessionContext>(); //设置NHibernate使用Redis缓存 //https://github.com/TheCloudlessSky/NHibernate.Caches.Redis var connectionMultiplexer = DiContainer.Resolve <ConnectionMultiplexer>(); RedisCacheProvider.SetConnectionMultiplexer(connectionMultiplexer); //设置Redis的序列化器 var options = new RedisCacheProviderOptions() { Serializer = new NhJsonCacheSerializer(), KeyPrefix = "Sopcce" }; RedisCacheProvider.SetOptions(options); //设置NHibernate在表结构变化时自动更新缓存 //https://github.com/TheCloudlessSky/NHibernate.Cache.DynamicCacheBuster new CacheBuster().AppendVersionToCacheRegionNames(configure); _sessionFactory = configure.BuildSessionFactory(); }
protected static HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.AddMapping <Models.urunMap>(); mapper.AddMapping <Models.dukkanMap>(); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); return(mapping); }
static FactoryProvider() { var modelInspector = new MySimpleModelInspector(); Assert.IsNotNull(new Entity()); var mapper = new ModelMapper(modelInspector); mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); mapper.BeforeMapClass += (mi, type, map) => map.Id(idmap => idmap.Generator(Generators.HighLow, gmap => gmap.Params(new { table = "NextHighVaues", column = "NextHigh", max_lo = 100, where = String.Format("EntityName = '{0}'", type.Name.ToLowerInvariant()) }))); mapper.BeforeMapClass += (mi, t, map) => map.Table(t.Name.ToLowerInvariant()); mapper.BeforeMapJoinedSubclass += (mi, t, map) => map.Table(t.Name.ToLowerInvariant()); mapper.BeforeMapUnionSubclass += (mi, t, map) => map.Table(t.Name.ToLowerInvariant()); mapper.BeforeMapProperty += (mi, propertyPath, map) => { if (typeof(decimal).Equals(propertyPath.LocalMember.GetPropertyOrFieldType())) { map.Type(NHibernateUtil.Currency); } }; mapper.BeforeMapBag += (mi, propPath, map) => { map.Cascade(Cascade.All.Include(Cascade.DeleteOrphans)); map.BatchSize(10); }; mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes()); var domainMapping = mapper.CompileMappingForEachExplicitlyAddedEntity(); domainMapping.WriteAllXmlMapping(); var configuration = new Configuration(); configuration.DataBaseIntegration(c => { c.Dialect<MsSql2008Dialect>(); c.ConnectionString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=IntroNH;Integrated Security=True;Pooling=False"; c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; c.SchemaAction = SchemaAutoAction.Create; }); foreach(var mapping in domainMapping) { configuration.AddMapping(mapping); } configuration.AddAuxiliaryDatabaseObject(CreateHighLowScript(modelInspector, Assembly.GetExecutingAssembly().GetExportedTypes())); Factory=configuration.BuildSessionFactory(); }
protected static HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.AddMapping <Models.CalisanlarMap>(); mapper.AddMapping <Models.DepartmanlarMap>(); //mapper.AddMapping<PackageMap>(); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); return(mapping); }
protected override void PostProcessConfiguration(NHibernate.Cfg.Configuration config) { base.PostProcessConfiguration(config); var mapper = new ModelMapper(); foreach (var asm in ClassMappingAssemblies.Select(Assembly.Load)) { mapper.AddMappings(asm.GetTypes()); } foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity()) { config.AddMapping(mapping); } }
protected override void PostProcessConfiguration(NHibernate.Cfg.Configuration config) { base.PostProcessConfiguration(config); // add any conformist mappings in the listed assemblies: var mapper = new ModelMapper(); foreach (var asm in ConformistMappingAssemblies.Select(Assembly.Load)) { mapper.AddMappings(asm.GetTypes()); } foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity()) { config.AddMapping(mapping); } }
/// <summary> /// Load the configurations that are configured with the ClassMap convention (NHibernate 3.2+) /// </summary> /// <param name="configuration"></param> /// <returns></returns> private Configuration LoadMappings(Configuration configuration) { // This configuration for mapper files ModelMapper mapper = new ModelMapper(); mapper.BeforeMapProperty += new PropertyMappingHandler(mapper_BeforeMapProperty); List <Type> typeList = m_ExtensionConfig.Assembly.GetMatchingTypesInAssembly(item => m_ExtensionConfig.MappingsNamespace.Equals(item.Namespace)).ToList(); mapper.AddMappings(typeList); IEnumerable <HbmMapping> mappings = mapper.CompileMappingForEachExplicitlyAddedEntity(); mappings.ForEach(m => configuration.AddMapping(m)); if (DumpToXML) { mappings.WriteAllXmlMapping(); } return(configuration); }
/// <summary> /// Override to give the configuration of mapping by code assemblies /// </summary> /// <param name="config"></param> protected override void PostProcessConfiguration(NHibernate.Cfg.Configuration config) { base.PostProcessConfiguration(config); // add any conformist mappings in the listed assemblies: var mapper = new ModelMapper(); //mapper.AddMappings(Assembly.GetAssembly(typeof(SecurityMap)).GetExportedTypes()); mapper.AddMappings(Assembly.GetAssembly(typeof(OrderMap)).GetExportedTypes()); mapper.AddMappings(Assembly.GetAssembly(typeof(FillMap)).GetExportedTypes()); mapper.AddMappings(Assembly.GetAssembly(typeof(TradeMap)).GetExportedTypes()); mapper.AddMappings(Assembly.GetAssembly(typeof(StrategyMap)).GetExportedTypes()); foreach (var asm in ConformistMappingAssemblies.Select(Assembly.Load)) { mapper.AddMappings(asm.GetTypes()); } foreach (var mapping in mapper.CompileMappingForEachExplicitlyAddedEntity()) { config.AddMapping(mapping); } }
/// <summary> /// ایجاد تنظیامت /// </summary> /// <returns></returns> private static Configuration createConfiguration() { ///[Creating configuration] var configuration = new Configuration(); //Loads nhibernate mappings configuration.DataBaseIntegration(db => { if (m_inMemory) { db.ConnectionString = "Data Source=:memory:;Version=3;New=True"; db.ConnectionProvider <SqLiteInMemoryTestingConnectionProvider>(); } else { db.ConnectionStringName = m_connectionStringName; } db.Dialect <NHibernate.Dialect.SQLiteDialect>(); db.BatchSize = 500; db.LogSqlInConsole = true; db.Driver <NHibernate.Driver.SQLite20Driver>(); }).SessionFactory().GenerateStatistics(); ModelMapper mapper = new ModelMapper(); mapper.AddMappings(m_typeMaps); foreach (HbmMapping mapping in mapper.CompileMappingForEachExplicitlyAddedEntity()) { configuration.AddMapping(mapping); } return(configuration); ///[Creating configuration] }
protected static HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.AddMapping<LocationMap>(); mapper.AddMapping<AddressMap>(); mapper.AddMapping<UserMap>(); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities(); return mapping; }
public void CanWriteMappingsReferencingProtectedProperty() { var mapper = new ModelMapper(); mapper.Class<Entity>(rc => { rc.Id(Entity.PropertyAccessExpressions.Id, m => m.Generator(Generators.GuidComb)); rc.Property(x => x.Name); }); mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping(); }