コード例 #1
0
        private static Configuration Configure()
        {
            var config = Fluently.Configure()
                         .Database(
                SQLiteConfiguration.Standard.UsingFile("database").ShowSql()
                //MsSqlConfiguration.MsSql2008.ConnectionString(b => b.FromConnectionStringWithKey("db"))
                )
                         .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AutomappingConfiguration(), GetAssemblies());
                model.Conventions.Add(new SetEnumTypeConvention());
                model.Conventions.Add(new UseNewSqlDateTime2TypeConvention());
                model.Conventions.Add(new CollectionAccessConvention());
                model.Conventions.Add(new SqlTimestampConvention());
                model.Conventions.Add(new SetTableNameConvention());

                model.Conventions.Add(DefaultLazy.Never());
                m.AutoMappings.Add(model);
                m.AutoMappings.ExportTo("c:\\mapping");
                m.FluentMappings.ExportTo("c:\\mapping");
            })
                         .BuildConfiguration();

            // Generatre schema before each start
            var e = new SchemaExport(config);

            e.SetOutputFile(@"c:\mapping\a.sql");
            e.Execute(true, true, false);

            return(config);
        }
コード例 #2
0
        private ISessionFactory CreateSessionFactory(IServiceFactory serviceFactory)
        {
            NHibernateConnectionProvider
            .SetAppSettingsService(serviceFactory.GetInstance <IAppSettingsRetriever>());

            var config = Fluently.Configure()
                         .Database(PostgreSQLConfiguration.PostgreSQL82
                                   .ShowSql()
                                   .FormatSql()
                                   .Provider <NHibernateConnectionProvider>()
                                   .Dialect <PostgreSQL82Dialect>()
                                   .AdoNetBatchSize(100))
                         //.CurrentSessionContext("call") // TODO ajustar o currentsessioncontext ainda..
                         //https://github.com/nhibernate/nhibernate-core/issues/1632
                         .Mappings(x => x.FluentMappings
                                   .AddFromAssemblyOf <LightInjectModule>()

                                   .Conventions.Setup(c =>
            {
                c.Add(DefaultLazy.Never());
            }))
                         .ExposeConfiguration(c =>
            {
                //c.SetProperty(Environment.DefaultFlushMode, FlushMode.Always.ToString());
                c.SetProperty(Environment.Hbm2ddlKeyWords, "keywords");         // http://fabiomaulo.blogspot.com/2009/06/auto-quote-tablecolumn-names.html


                //https://stackoverflow.com/questions/2134565/how-to-configure-fluent-nhibernate-to-output-queries-to-trace-or-debug-instead-o
                c.SetInterceptor(new SqlLoggingInterceptor());
            })
                         .BuildConfiguration();

            return(config.BuildSessionFactory());
        }
コード例 #3
0
        static void SetDefaultConfig(FluentConfiguration config)
        {
            config.Mappings(c =>
            {
                c.FluentMappings.Conventions.AddFromAssemblyOf <EnumConvention>();
                var hbmXmlPath = Path.Combine(PathHelper.AppDataPath, "hbmXml");
                DirectoryHelper.CreateIfNotExists(hbmXmlPath);
                c.FluentMappings.AddFromAssembly(_entityMapAssembly).ExportTo(hbmXmlPath);
                c.FluentMappings.Conventions.Add(DefaultLazy.Never());
                c.FluentMappings.Conventions.Add(
                    ConventionBuilder.HasMany.Always(x =>
                {
                    x.Fetch.Join();
                }),
                    ConventionBuilder.HasManyToMany.Always(x =>
                {
                    x.Fetch.Join();
                }),
                    ConventionBuilder.Reference.Always(x =>
                {
                    x.ReadOnly();
                    x.Fetch.Join();
                    x.Nullable();
                    x.NotFound.Ignore();
                }));
            });

            config.Cache(x => x.ProviderClass <NoCacheProvider>());
        }
コード例 #4
0
 private static void InitializeSessionFactory()
 {
     mSessionFactory = Fluently.Configure()
                       .Database(SQLiteConfiguration.Standard.UsingFile(DatabaseFile).ShowSql())
                       .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())
                                 .Conventions.Add(DefaultLazy.Never()))
                       .BuildSessionFactory();
 }
コード例 #5
0
        public static AutoPersistenceModel CreateMappings()
        {
            var cfg = new DbMapConfiguration();

            return(AutoMap.Assemblies(cfg, AppDomain.CurrentDomain.GetAssemblies())
                   .Conventions.Add(DefaultLazy.Never()));
            //.Where(t => t.Namespace == "CQRS2012");
        }
コード例 #6
0
 public void NeverShouldSetDefaultLazyToFalse()
 {
     model.Add(new ClassMap <Target>());
     model.Conventions.Add(DefaultLazy.Never());
     model.BuildMappings()
     .First()
     .DefaultLazy.ShouldBeFalse();
 }
コード例 #7
0
 private static void GetMappings(MappingConfiguration x)
 {
     x.AutoMappings
     .Add(
         AutoMap.AssemblyOf <IngredientDTO>(new MealPlannerAutomappingConfiguration())
         .Conventions.Add(DefaultLazy.Never())
         );
 }
コード例 #8
0
 public UnitOfWork()
 {
     session = Fluently.Configure()
               .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(x => x.FromConnectionStringWithKey("ConnectionString")).ShowSql())
               //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
               .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())
                         .Conventions.Add(DefaultLazy.Never()))
               .BuildSessionFactory()
               .OpenSession();
 }
コード例 #9
0
        void DiscoverClassMapsAndAddAssemblies(ITypeDiscoverer typeDiscoverer, MappingConfiguration mappings)
        {
            var assemblies = typeDiscoverer.FindMultiple(typeof(IMappingProvider)).Select(t => t.Assembly).Distinct();

            foreach (var assembly in assemblies)
            {
                mappings.FluentMappings.AddFromAssembly(assembly).Conventions.Add(DefaultLazy.Never(), AutoImport.Never());
                mappings.HbmMappings.AddFromAssembly(assembly);
            }
        }
コード例 #10
0
        public static IUnitOfWorkConfiguration GetConfiguration()
        {
            Configuration config = Fluently.Configure()
                                   .Database(SQLiteConfiguration.Standard.UsingFile("security.s3db"))
                                   .Mappings(m => m.FluentMappings
                                             .AddFromAssemblyOf <PermissionRepository>()
                                             .Conventions.Add(DefaultLazy.Never())
                                             ).BuildConfiguration();

            return(new NHibernateConfig(() => config, new StructureMapRepositoryFactory(), new ThreadStaticUnitOfWorkStorage()));
        }
コード例 #11
0
 private static ISessionFactory BuildSessionFactory()
 {
     return(Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnectionString)
                      .ShowSql())
            .Mappings(m => m.FluentMappings
                      .AddFromAssembly(Assembly.GetExecutingAssembly())
                      .Conventions.Add(DefaultLazy.Never()))
            .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                 .Create(false, false))
            .BuildSessionFactory());
 }
コード例 #12
0
        private static void CreateSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                              .Database(MsSqlConfiguration.MsSql2012.ConnectionString("Data Source=.;Initial Catalog=HowLongDb;Integrated Security=SSPI;").ShowSql)
                              .Mappings(m =>
                                        m.FluentMappings.AddFromAssemblyOf <NHibernateHelper>() // NHibernate, olhe o assembly onde está a classe Serie e procure por arquivos de mapemanento que eu conheça (que são classes que herdam de ClassMap).
                                        .Conventions.Add(DefaultLazy.Never()))                  // para não precisar do Virtual na classe
                              .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
                                                                                                //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))

                              .BuildSessionFactory();
        }
コード例 #13
0
        private void AddMappings(MappingConfiguration mappingConfiguration)
        {
            var m = mappingConfiguration.FluentMappings;

            m.Add <UserMapping>();
            m.Add <VehicleMapping>();
            m.Add <EmployeeMapping>();
            m.Add <BusinessUnitMapping>();
            m.Add <VehicleToEmployeeRelationMapping>();

            m.Conventions.Add(DefaultLazy.Never());
        }
コード例 #14
0
        public ISessionFactory CreateFactory(string connectionString)
        {
            var nhibcfg = new NHibernate.Cfg.Configuration();

            var cfg = Fluently.Configure(nhibcfg)
                      .Database(
                PostgreSQLConfiguration
                .Standard
                .ConnectionString(connectionString)
                )
                      .Mappings(m =>
            {
                m.AutoMappings.Add(AutoMap.AssemblyOf <Banan>(new AutomappingConfiguration())
                                   .Conventions.Setup
                                   (
                                       con =>
                {
                    con.Add <CommonConventions>();
                    con.Add(DefaultLazy.Never());
                    con.Add(DefaultCascade.SaveUpdate());
                    con.Add(DynamicInsert.AlwaysTrue());
                    con.Add(DynamicUpdate.AlwaysTrue());
                }).UseOverridesFromAssemblyOf <OvverideMappingsFatherBanan>());

                m.FluentMappings.Conventions.Add <CommonConventions>();
                m.FluentMappings.Conventions.Add(DefaultLazy.Never(), DefaultCascade.SaveUpdate(), DynamicInsert.AlwaysTrue(), DynamicUpdate.AlwaysTrue());
                m.MergeMappings();
            });

            if (true)
            {
                var directory = $"BananFatherDatabase.HBM";
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                cfg.Mappings(m => m.AutoMappings.ExportTo(directory));
            }

            cfg.ExposeConfiguration(c => SchemaMetadataUpdater.QuoteTableAndColumns(c, new PostgreSQLDialect()));
            cfg.ExposeConfiguration(c => c.SetProperty("command_timeout", "30"));

            cfg.ExposeConfiguration(x =>
            {
                x.SetInterceptor(new SqlStatementInterceptor());
            });

            UpdateSchema(cfg.BuildConfiguration());

            return(cfg.BuildSessionFactory());
        }
コード例 #15
0
        private NHibernateHelper()
        {
            _configuration = Fluently.Configure()
                             .Database(GetDatabaseConfigurer)
                             .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf <Order>(new AutomappingConfiguration())
                                                               .IgnoreBase(typeof(EventLog <, ,>))
                                                               .IgnoreBase(typeof(OrderParameterEventLog <>))
                                                               .Conventions.Add(
                                                                   DefaultLazy.Never()
                                                                   )));

            _sessionFactory = _configuration
                              .ExposeConfiguration(v => new SchemaExport(v).Create(false, false))
                              .BuildSessionFactory();
        }
コード例 #16
0
        public static IConvention[] AllConventions(string referenceSuffix = "", bool toLowercase = true)
        {
            IList <IConvention> lcase =
                new IConvention[]
            {
                Table.Is(x => x.EntityType.Name.ToLowercaseNamingConvention(toLowercase))
                , ConventionBuilder.Property.Always(x => x.Column(x.Name.ToLowercaseNamingConvention(toLowercase)))
                , ConventionBuilder.Id.Always(x => x.Column(x.Name.ToLowercaseNamingConvention(toLowercase)))
                , LowercaseForeignKey.EndsWith(referenceSuffix, toLowercase),
                new ColumnNullabilityConvention(),
                DefaultLazy.Never()
            };

            return(lcase.ToArray());
        }
コード例 #17
0
        private static ISessionFactory BuildSessionFactory(string connectionString)
        {
            FluentConfiguration configuration = Fluently.Configure()
                                                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString))
                                                .Mappings(m => m.FluentMappings
                                                          .AddFromAssembly(Assembly.GetExecutingAssembly())
                                                          .Conventions.Add(
                                                              ForeignKey.EndsWith("ID"),
                                                              ConventionBuilder.Property
                                                              .When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()))
                                                          .Conventions.Add <TableNameConvention>()
                                                          .Conventions.Add <HiLoConvention>()
                                                          .Conventions.Add(DefaultLazy.Never())
                                                          );

            return(configuration.BuildSessionFactory());
        }
コード例 #18
0
        public static ISessionFactory GetSessionFactory()
        {
            if (null == _sessionFactory)
            {
                FluentConfiguration nhConfig = Fluently.Configure()
                                               .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(
                        c =>
                        c.Database(_conn.InitialCatalog).Server(_conn.DataSource).TrustedConnection()))
                                               .Mappings(m =>
                                                         m.FluentMappings.AddFromAssemblyOf <Itens>()
                                                         .Conventions.Add(DefaultLazy.Never()));

                nhConfig.Cache(c => c.ProviderClass <SysCacheProvider>().UseSecondLevelCache());
                _sessionFactory = nhConfig.ExposeConfiguration(v => new SchemaExport(v).Create(false, false)).BuildSessionFactory();
            }
            return(_sessionFactory);
        }
コード例 #19
0
ファイル: OrderUnityOfWork.cs プロジェクト: Helderf85/my-repo
 private static ISessionFactory BuildSessionFactory()
 {
     try
     {
         return(Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(@"Data Source=LAPTOP-VQPN3HBJ;Initial Catalog=Db_Order;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
                .Mappings(m => m.FluentMappings
                          .AddFromAssembly(Assembly.GetExecutingAssembly())
                          .Conventions
                          .Add(DefaultLazy.Never()))
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)).BuildSessionFactory());
         //primeira vez que se cria o banco tem que estar true depois sempre false
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #20
0
        public ISessionFactory CreateSessionFactory()
        {
            return(Fluently.Configure().Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnectionString)
                    #if DEBUG
                                                 .ShowSql()
                    #endif
                                                 )

                   .Mappings(m => m.FluentMappings
                             .AddFromAssemblyOf <Program>()
                             .Conventions.Setup(c =>
            {
                c.Add(DefaultLazy.Never());
            }))

                   .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                        .Execute(true, false, false))
                   .BuildSessionFactory());
        }
コード例 #21
0
 public static ISessionFactory GetSessionFactory()
 {
     return(Fluently
            .Configure()
            .Database(
                MsSqlConfiguration
                .MsSql2012
                .ConnectionString(conn => conn.FromConnectionStringWithKey("connection")))
            .Mappings(m =>
                      m.FluentMappings
                      .AddFromAssemblyOf <UnitOfWork>()
                      .Conventions.Add(DefaultLazy.Never()))
            .ExposeConfiguration(cfg =>
     {
         cfg.SetInterceptor(new SqlStatementInterceptor());
         cfg.EventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] { new SoftDeletableListener() };
         new SchemaExport(cfg).Create(false, true);     // generate the DB schema but do not trace
     })
            .BuildSessionFactory());
 }
コード例 #22
0
        public ISessionFactory Build()
        {
            var assemblies    = System.AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("Infra"));
            var configuration = Fluently.Configure()
                                .Database(MySQLConfiguration.Standard.ConnectionString(Env.GetString("DB_CONNECTION_STRING")))
                                .Mappings(mappings =>
            {
                assemblies.ForEach(assembly => mappings.FluentMappings.AddFromAssembly(assembly));
                mappings.FluentMappings.Conventions.Setup(config =>
                {
                    config.Add(DefaultLazy.Never());
                    config.Add(ForeignKey.EndsWith("Id"));
                });
            })
                                .ExposeConfiguration(config =>
            {
                config.EventListeners.PostCommitInsertEventListeners = new IPostInsertEventListener[]
                {
                    new NHibernateEvents(eventHandler)
                };

                config.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[]
                {
                    new NHibernateEvents(eventHandler)
                };

                config.EventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[]
                {
                    new NHibernateEvents(eventHandler)
                };

                config.EventListeners.PostCommitDeleteEventListeners = new IPostDeleteEventListener[]
                {
                    new NHibernateEvents(eventHandler)
                };
            });

            return(configuration.BuildSessionFactory());
        }
コード例 #23
0
ファイル: NHibernateHelper.cs プロジェクト: fraidev/Checklist
        public static ISessionFactory CreateSessionFactory()
        {
            return(Fluently.Configure()
                   .Database(MsSqlConfiguration.MsSql2012
                             .ConnectionString("Data Source=.;Initial Catalog=ChecklistDB;Integrated Security=SSPI;")
                             .ShowSql())

                   .Mappings(m => m.FluentMappings

                             .AddFromAssemblyOf <Program>()
                             .Conventions.Setup(c =>
            {
                c.Add(DefaultLazy.Never());          // Acabar com os virtual
                //  c.Add(DefaultCascade.All());
            }))

                   .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                        // .Create(true, true)
                                        )

                   .BuildSessionFactory());
        }
コード例 #24
0
        private AutoPersistenceModel CreateMappings()
        {
            var mappingSetup = AutoMap
                               .AssemblyOf <TEntity>()
                               .Where(x =>
                                      !typeof(IAutoMapperSettings).IsAssignableFrom(x) && //ignore all classes that implement auto mapper settings.
                                      !x.IsSubclassOf(typeof(BaseRepo)) && //ignore all classes that inherit from nhibernate base repo class
                                      !x.IsSubclassOf(typeof(RepoSplit <TEntity, TOverride>)) && //ignore all classes that inherit from nhibernate repo class
                                      !x.IsSubclassOf(typeof(RepoCombined <TEntity>)) && //ignore all classes that inherit from nhibernate repo class
                                      !typeof(IClassConvention).IsAssignableFrom(x) && //ignore all NHibernate convention classes
                                      !x.IsSubclassOf(typeof(AbstractBaseMigration)) && //ignore all migration files.
                                      !x.IsSubclassOf(typeof(RepoMigrationConfigurationBaseNoneGeneric)) //ignore all migration configuration files.
                                      )

                               .Conventions.AddFromAssemblyOf <TOverride>()

                               .UseOverridesFromAssemblyOf <TOverride>()
                               .Conventions.Add(DefaultLazy.Never())
                               .Conventions.Add(DefaultCascade.SaveUpdate());

            return(mappingSetup);
        }
コード例 #25
0
        static void DiscoverClassMapsAndAddAssemblies(
            IAssemblies assemblies,
            ITypeDiscoverer typeDiscoverer,
            MappingConfiguration mappings)
        {
            var assembliesWithFluentMappings = typeDiscoverer
                                               .FindMultiple(typeof(IMappingProvider))
                                               .Select(t => t.Assembly)
                                               .Distinct();

            foreach (var assembly in assembliesWithFluentMappings)
            {
                mappings.FluentMappings.AddFromAssembly(assembly).Conventions.Add(DefaultLazy.Never(), AutoImport.Never());
            }

            var assembliesWithHbmMappings = assemblies
                                            .GetAll()
                                            .Where(a => a.GetManifestResourceNames().Any(s => s.EndsWith(".hbm.xml")));

            foreach (var assembly in assembliesWithHbmMappings)
            {
                mappings.HbmMappings.AddFromAssembly(assembly);
            }
        }
コード例 #26
0
        internal static FluentConfiguration NHibernateConfiguration(string connectionString, bool updateDatabase = false)
        {
            var config = Fluently.Configure();
            var pgsql  = PostgreSQLConfiguration.Standard;

            pgsql.Dialect <NHibernate.Dialect.PostgreSQL83Dialect>();
            pgsql.ConnectionString(connectionString);

            config.Database(pgsql);
            config.Mappings(m => m.FluentMappings.AddFromAssemblyOf <Models.Core.UserGroup>().Conventions.Add(DefaultLazy.Never()));
            config.ExposeConfiguration(cfg => cfg.SetInterceptor(new SqlStatementInterceptor()));

            if (updateDatabase)
            {
                config.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true));
            }

            return(config);
        }
コード例 #27
0
ファイル: Startup.cs プロジェクト: eldersontc/SNACKS
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //NHibernate
            services.AddSingleton <ISessionFactory>((provider) => {
                return(Fluently.Configure()
                       .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2012
                                 .ConnectionString(Configuration.GetConnectionString("DefaultConnection")).ShowSql())
                       .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Pedido>().Conventions.Add(DefaultLazy.Never()))
                       .BuildSessionFactory());
            });

            services.AddScoped <IRepBase, RepBase>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc().AddJsonOptions(configureJson);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }